2016-09-20 90 views
0

我是arduino的新手,我想做多線程編程。 我寫了一些代碼,我想要下面的代碼來更新變量tempsPose,但它不起作用(Led總是以相同的速度閃爍)。arduino線程更新易失性變量

我怎樣才能更改下面的代碼,以便更新「tempsPose」在功能blinkled13變量時,該變量在循環功能mofified

非常感謝您的幫助

#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

例子都是「一次性」(沒有無限循環),代碼if (thread.shouldRun()) thread.run();loop()之內。所以我想它根本不會進入loop()

例如多個交互式代碼( '+' 增加了100毫秒, ' - ' substracts 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); 
    } 
} 
+0

與上面的代碼中,LED 13不會停止blinkink(而(1)中的函數)但延遲不會隨着時間而改變 – user3052784

+0

那是因爲它從未離開過'blinkLed13'。它永遠不會進入「循環」來改變延遲。只需將這些更改的值打印到串行中即可。因爲它在'setup'函數和'myThread.run()' – KIIV

+0

被困住了,所以沒有任何東西,謝謝你的評論,但是我不太瞭解你寫的東西。你能告訴我一些代碼嗎? – user3052784