我想在Arduino中使用多线程编程。
我写了一些代码ato更新变量tempsPose
但是它没有工作(led闪烁始终以相同的速度)。
当在循环函数中修改此变量时,如何更改以下代码以更新函数tempsPose
中的blinkled13
变量?
#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;
}
}
答案 0 :(得分:0)
例子都是&#34;一次性&#34; (没有无限循环),代码if (thread.shouldRun()) thread.run();
位于loop()
内。所以我想在你的情况下根本不会进入loop()
。
例如,更多互动代码(&#39; +&#39;添加100毫秒,&#39; - &#39;减去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);
}
}