Friday, 27 September 2013 20:40

Arduino BIT manipulations

Written by
Code below set third pin to HIGH without changing the state of any of the other pins
bitSet syntax: bitSet(x, n)
  • x: the numeric variable whose bit to set
  • n: which bit to set, starting at 0 for the least-significant (rightmost) bit

//initialized all pins to LOW
byte pinState = B00000000;

//set the third pin high
bitSet(pinState, 2); //pinState = B00000100

 
  
Code below set third pin to LOW without changing the state of any of the other pins
bitClear syntax: bitClear(x, n)
  • x: the numeric variable whose bit to clear
  • n: which bit to clear, starting at 0 for the least-significant (rightmost) bit

//initialized all pins to HIGH
byte pinState = B11111111;

//set the third pin LOW
bitClear(pinState, 2); //pinState = B11111011

 
 
Code below set each pin as LOW or HIGH without changing the state of any of the other pins
bitWrite Syntax: bitWrite(x, n, b)
  • x: the numeric variable to which to write
  • n: which bit of the number to write, starting at 0 for the least-significant (rightmost) bit
  • b: the value to write to the bit (0 or 1)
byte pinState= 0; //initialized all pins to LOW (B00000000)
bitWrite(pinState, 0, HIGH); //set first pin to HIGH, pinState = B00000001
bitWrite(pinState, 3, HIGH); //set third pin to HIGH, pinState = B00001001
bitWrite(pinState, 0, LOW); //set first pin to LOW, pinState = B00001000
 
 
Reads a bit of a number.
bitRead Syntax: bitRead(x, n)
  • x: the number from which to read
  • n: which bit to read, starting at 0 for the least-significant (rightmost) bit

byte pinState = B10101010;
for (int i=0; i<8; i++) {
   theBit = bitRead(pinState, i);
}

 

 

Read 24959 times Last modified on Monday, 30 September 2013 17:33
Back to Top