volatile
volatile 是 C 語言內定的關鍵字之一,它用在宣告變數的資料型態之前,讓編譯器還有後續的程式碼改變對它的操作方式。
宣告一個變數為 volatile 可以引導編譯器的行為。編譯器是能將 C/C++ 語言程式碼轉換成機器碼的軟體,轉換後的機器碼則由 86Duino CPU 去執行。
volatile 的特別之處在於,它引導編譯器從 RAM 中載入變數而不是從暫存器(暫存器是程式暫時儲存與調出變數的空間)。在某些情況下將變數數值存到暫存器可能會不準確。
如果變數可能會被其他同時處理的執行緒修改時,應該宣告成 volatile (例如:中斷副程式和使用者程式共用的全域變數)。在 86Duino 中只有控制中斷 (interrupt) 的中斷副程式 (interrupt service routine) 有關的地方可能會發生這種情況。
範例
// 當 LED 的開關觸發時,切換 pin 腳狀態
int pin = 13;
volatile int state = LOW;
void setup()
{
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);
}
void loop()
{
digitalWrite(pin, state);
}
void blink()
{
state = !state;
}
See also
- attachInterrupt()
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.
