在Arduino中設定/清除數字的特定位
當您深入研究高階韌體時,會處理許多暫存器,其特定位需要根據您的用例進行設定或清除。Arduino 有內建函式可以做到這一點。
語法
bitSet(x, index)
和,
bitClear(x, index)
其中 x 是需要設定/清除其位的數字,index 是位的位 置(0 表示最低有效位或最右邊的位)。此函式就地更改數字 x,並返回 x 的更新值。
請注意,設定一位表示將其值設定為 1,清除一位表示將其值設定為 0。
示例
以下示例說明了這些函式的使用:
void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); int x = 6; Serial.println(x); bitSet(x,0); Serial.println(x); bitClear(x,2); Serial.println(x); bitClear(x,3); Serial.println(x); } void loop() { // put your main code here, to run repeatedly: }
輸出
序列埠監視器輸出如下所示:
如您所見,我們從數字 6 (0b0110) 開始。
然後我們設定其第 0 位,得到 (0b0111),對應於 7。
然後,我們清除其第 2 位,得到 (0b0011),對應於 3。
然後我們清除其第 3 位,該位已經為 0。因此,我們再次得到 (0b0011),對應於 3。
序列埠監視器輸出按我們剛才描述的精確順序顯示這些數字。
廣告