Showing posts with label bit logic. Show all posts
Showing posts with label bit logic. Show all posts

Thursday, August 25, 2011

Task 15 - Byte output using RS232 soft-serial protocol

Arduino RS232 soft-serial protocol

Task 14 - Arbitrary byte serial monitor output bit-by-bit

/*
 * Project:    bitwiseByteOutput_task14
 * Author:     Jane-Maree Howard
 * Date:         Wednesday 24/08/2011; modified Sunday 09/10/2011
 * Platform:   Arduino 22
 * Purpose:    To output the bits, one by one, to the
  =                  serial monitor(SM) screen from an arbitrary byte.
 * Operation:  Inputs an arbitrary byte, which is right-shifted 0 to 7 places
 -             successively, bit-wise ANDed with value B01, & each resultant bit is
 -             separately outputted to the SM
 -             Arduino Libraries: LIB04_KeypressInput; LIB05_BitSelect;
 -             Declare: Function bitwiseByte(bByte,iShifts); int iKeyPress; byte bInbyte;
 -             Setup(): Serial @ 9600 baud; headings             
 -             Loop():  Input keypress as arbitrary byte; output byte as BINary;
 -                      output each bit separately
 */
int     iKeyPress = 0;       // for incoming serial data 
byte    bInbyte;
void setup()  
{
  Serial.begin(9600);        // Serial @ 9600 baud
  // print headings
  Serial.println("KEY-PRESS\tBIN\tLSB..................MSB");  
}//end setup()

void loop()                    

  // send data only when you receive data
  iKeyPress = KeypressInput();       // LIB04_KeypressInput
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);   // print as ASCII character
    Serial.print("\t\t");                    // print tabs
    bInbyte  = iKeyPress;      //
    Serial.print(bInbyte, BIN);         // print resultant byte as binary
    Serial.print("\t");                      // print tab
    for (int j=0; j<8; j++)                 // now select each bit separately
    {
      bInbyte  = iKeyPress;
      bInbyte  = BitSelect(bInbyte, j);     // LIB05_BitSelect
      Serial.print(bInbyte, BIN);             // ..print each bit..
      Serial.print("  ");                           // ..& 2 spaces
    }//for()
    Serial.println(); 
  }//if()  
}//end loop()
//END


As can be seen, the BIN column entries
are 'mirror-imaged' by the block labelled LSB............MSB since we start with the Least Significant Bit.  Leading zeroes omitted in the BIN column give the output a slightly unbalanced look.

 LIB04_KeypressInput
 see Task 13

 /*
 * Project:    LIB05_BitSelect
 * Author:     Jane-Maree Howard
 * Date:         Sunday 09/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library    function for selecting a given bit         from an arbitrary byte
 * Operation:  Bitwise ANDs arbitrary byte with value B01
 -                    after being right-shifted a given number of places
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE
 -             Procedure(): byte BitSelect(byte, byte);     
 -             Loop():      NONE          
 */
byte BitSelect(byte bByte, byte bShift)
{
  /*  bitwise ANDs parameter bByte with value B01
      after being right-shifted bShift places
      & returns a separate Byte
      CALLED IN MAIN SKETCH  */
  bByte      = bByte >> bShift;
  bByte      = bByte & B01;
  return bByte;
}//BitSelect()
//END

Task 13 - byte left-shifting function

/*
 * Project:      ByteLeftShift_621task13
 * Author:     Jane-Maree Howard
 * Date:         Wednesday 21/09/2011; modified Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To left-shift a byte in the parameter postion two places to the left
 -                   then output the original and the final byte.
 * Operation:  Description: Prints headings; inputs character;
 -             Arduino Libraries: LIB04_KeypressInput (see below);
 -             Declare: Function leftShiftByte(bByte,iShifts); int iKeyPress; byte bInbyte;
 -             Setup():             
 -             Loop():                   
 */
int     iKeyPress = 0;       // for incoming serial data 
byte    bInbyte;
void setup()  
{
  Serial.begin(9600);       // Serial @ 9600 baud
  // print headings
  Serial.println("KEY-PRESS\tBIN\tSHIFTED");  
}//end setup()

void loop()                    
{
   // send data only when you receive data
  iKeyPress = KeypressInput();       // LIB04_KeypressInput
(see below)
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);    // print as ASCII character
    Serial.print("\t\t");                     // print tabs
    bInbyte  = iKeyPress;      //
    Serial.print(bInbyte, BIN);          // print resultant byte as binary
    Serial.print("\t");                        // print tab
    bInbyte  = leftShiftByte(bInbyte,2);  // left-shift 2 places &..
    Serial.println(bInbyte, BIN);             // ..print resultant byte as binary
  }//if()  
}//end loop()

// leftShiftByte() - left-shifts parameter byte iShift places
byte leftShiftByte(byte bByte,int iShift)
{
  bByte  = bByte << iShift;
  return bByte;
}//leftShiftByte()
//END



 The left-shifted byte is clear from the screen-print  
 on the right. 


Leading zeros omitted (in the BIN column & the SHIFTED column) .


Below is my Arduino Library function for Serial input.


 /*
 * Project:     LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link
 * Operation:  Description: inputs a key-press & returns an Integer
 -                    Procedure(): int KeypressInput();  no parameters             
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
      & returns a non-zero Integer only if there is an input
      CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()


Task-14

Task 12 - byte LSB test function

/*
 * Project:    ByteLSBtest_621task12
 * Author:     Jane-Maree Howard
 * Date:       Wednesday 21/09/2011; modified Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    Function to say "yes" if the LSB (least significant bit) is a 1
 -              or "no" otherwise. Tested in the main loop.
 * Operation:  Description:  inputs keypress via Serial comm link;
 -                           A function taking the keypress integer as parameter
 -                           logically ANDs it with binary number B01,
 -                           producing a number which is equal to
 -                           either '1' or '0', & prints "yes" or "no" accordingly
 -             Arduino Library: LIB04_KeypressInput; LIB03_BinaryAND;
 -             Declare: Function LSBtest(bByte); (int)iKeyPress; (byte) bInbyte;
 -             Setup(): Serial comms @ 9600 baud; headings;           
 -             Loop():  input keypress; test LSB & print 'yes'/'no' result                 
 */
int     iKeyPress = 0;       // for incoming serial data 
byte    bInbyte;           // function parameter

void setup()  
{
  Serial.begin(9600);      // Serial comms @ 9600 baud
  // print headings
  Serial.println("KEY-PRESS\tBIN\tYES/NO");    
}//end setup()

void loop()                    

  // send data only when you receive data
  iKeyPress = KeypressInput();      // LIB04_KeypressInput - see below
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);   // print as ASCII character
    Serial.print("\t\t");                    // print tab      
    Serial.print(iKeyPress, BIN);     // print as BINary
    Serial.print("\t");                      // print tab
    bInbyte  = iKeyPress;
    LSBtest(bInbyte);                      // test LSB 
  }//if()
}//end loop()

// tests parameter's LSB for '1'/'0' & outputs "yes"/"no"
void LSBtest(byte bByte)
{
  // test LSB
  bByte  = BinaryAND(bByte, B01);  //
LIB03_BinaryAND - see below
  // there are only 2 possible values
  if (bByte == 0)
    Serial.println("NO");
  else
    Serial.println("YES");
}//LSBtest()
//END




self-explanatory..

(bit fuzzy tho')















/*
 * Project:    LIB03_BinaryAND
 * Author:     Jane-Maree Howard
 * Date:         Friday 07/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for bitwise ANDing 2 bytes
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE     
 -             Loop():      NONE       
 */
byte BinaryAND(byte bB1, byte bB2)
{
  /*  bitwise ANDs 2 Bytes together & returns a separate Byte
  -   CALLED IN MAIN SKETCH  */
  byte bOutByte  = bB1 & bB2;
  return bOutByte;
}//BinaryAdd()
//END

/*
 * Project:    LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link  

 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE     
 -             Loop():      NONE    
         
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
  -    & returns a non-zero Integer only if there is an input
  -    CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()
//END

Task 11 - bit-ANDing function

/*
 * Project:    BinaryANDing_621task11
 * Author:     Jane-Maree Howard
 * Date:         Wednesday 21/09/2011; modified Friday 07/10/2011
 * Platform:   Arduino 22
 * Purpose:    To demonstrate a function to bitwise AND a byte with B01
 -                   and output the result to the screen.
 -                   Tests in the main loop().
 * Operation: Inputs a byte via Serial comm & 

 -                   function taking a byte as parameter bitwise-ANDs it
 -                   with value B01
 -         Arduino Library: LIB03_BinaryAND - function BinaryAND(byte,byte)

 -                                    LIB04_KeypressInput  
 -             Declare:          byte bInbyte; int iKeyPress;
 -             Setup():          Serial comms @ 9600 baud; print heading              
 -             Loop():           Input a byte via Serial comm & output to SM as BIN;

 -                                   bitwise-AND byte with value B01 & output result to SM.                
 */
int     iKeyPress = 0;     // for incoming serial data 
byte    bInbyte;

void setup()  
{
  Serial.begin(9600);      //Serial @ 9600baud
  // print headings
  Serial.println("KEY-PRESS  BIN\t    AND b01"); 
}//end setup()

void loop()                    

  // send data only when you receive data
  iKeyPress = KeypressInput();       // LIB04_KeypressInput
  if (iKeyPress !=0)
  {
    Serial.print(iKeyPress, BYTE);   // print as ASCII character
    Serial.print("\t   ");           // print tabs
    bInbyte  = iKeyPress;            //
    Serial.print(bInbyte, BIN);      // print resultant byte as binary
    Serial.print("  ");              // print tab
    bInbyte  = BinaryAND(bInbyte, B01);   // LIB03_BinaryAND
    Serial.println(bInbyte, BIN);         // ..print resultant byte as binary
   }//if()  
}//end loop()
//END


At right is the Serial Monitor output showing what happens to a byte that is bitwise-ANDed with the value B01.

Only the LSB appears, as leading zeroes are ignored.



/*
 * Project:    LIB03_BinaryAND
 * Author:     Jane-Maree Howard
 * Date:         Friday 07/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for bitwise ANDing 2 bytes
 * Operation: bitwise ANDs 2 parameter bytes & returns a third byte
 -              Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -              Setup():     NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                              (used  only in testing)
 -              Procedure(): byte BinaryAND(byte, byte);     
 -              Loop():      NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                              (used  only in testing)            
 */
byte BinaryAND(byte bB1, byte bB2)
{
  /*  bitwise ANDs 2 Bytes together & returns a separate Byte
      CALLED IN MAIN SKETCH  */
  byte bOutByte  = bB1 & bB2;
  return bOutByte;
}//BinaryAdd()
//END


/*
 * Project:     LIB04_KeypressInput
 * Author:     Jane-Maree Howard
 * Date:         Saturday 08/10/2011
 * Platform:   Arduino 22
 * Purpose:    To make a library function for inputting a key-press via Serial comm link
 * Operation:  inputs a key-press & returns an Integer
 -             Declare:     NONE - MUST BE DECLARED IN CONJOINING SKETCH(ES)
 -             Setup():     NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                               (used  only in testing)
 -             Procedure(): int KeypressInput();  no parameters   
 -             Loop():      NONE - MUST BE USED ONLY IN CONJOINING SKETCH(ES)
 -                              (used  only in testing)            
 */
int KeypressInput()
{
  /*  inputs a keypress via the Serial comms link
      & returns a non-zero Integer only if there is an input
      CALLED IN MAIN SKETCH  */
  int iKey = 0;
  // send data only when you receive data
  if (Serial.available() > 0)
    iKey = Serial.read();
  return iKey;
}//KeypressInput()
//END
 

Task 10 - Binary Adding function

/*
 * Project:    BinaryAdding_621task10
 * Author:     Jane-Maree Howard
 * Date:       Tuesday 30/08/2011
 * Platform:   Arduino 22
 * Purpose:    To demonstrate a function to add B0111 to a byte passed to it.
 -             Called 256 times in loop() using 0-255 as the parameters.
 * Operation:  Description: A function taking a byte as parameter adds a specific
 -                          binary number to it & returns a byte
 -             Declare: Function binaryAdd(bByte); bThisByte
 -             Setup(): Serial port @ 9600 baud; print bThisByte.
 -             Loop():  Adds byte B0111 to given byte 256 times                 
 */
byte  bThisByte  = B01011010;
byte  bStoreByte;
void setup()  
{
  Serial.begin(9600);  //SM @ 9600baud
  Serial.print("\nByte = \t");
  Serial.println(bThisByte, BIN);
  Serial.println();
}//end setup()

void loop()                    
{
  bStoreByte   = bThisByte;    // stores byte being operated on..
  for (int j=0; j<256; j++)
  {
    bThisByte  =+ BinaryAdd(bThisByte);
    Serial.print("Byte = \t");
    Serial.println(bThisByte, BIN);
    delay(100);
  }//for()
  Serial.print("\nStored: ");
  Serial.print(bStoreByte, BIN);
  Serial.println(",\t+ the 256 additions.\n");
  delay(2000);
}//end loop()

// BinaryAdd() - adds B00000111 to parameter
byte BinaryAdd(byte bByte)
{
  bByte = bByte + B00000111;
  return bByte;
}//BinaryAdd()
//END



The screen-shot on the right
shows the start of the program.


Byte = 1011010



On the left, you can see the byte
just above the stored byte - it's
exactly the same value..


..& again, the same value, although the program has gone through several more loop() cycles, as you
can see by the position of the
cursor at the right of the Serial
Monitor.


The value remains 1011010.

Arduino Bit-operations AND, OR, XOR


Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^)


The bitwise operators perform their calculations at the bit level of variables.
They help solve a wide range of common programming problems.
Much of the material below is from an excellent tutorial on bitwise math wihch may be found here.

Description and Syntax


Below are descriptions and syntax for all of the operators.
Further details may be found in the referenced tutorial.

Bitwise AND (&)


The bitwise AND operator in C++ is a single ampersand, &,
    used between two other integer expressions.
Bitwise AND operates on each bit position of the surrounding expressions independently,
    according to this rule:
    if both input bits are 1, the resulting output is 1, otherwise the output is 0.
Another way of expressing this is:

    0  0  1  1    operand1
    0  1  0  1    operand2
    ----------
    0  0  0  1    (operand1 & operand2) - returned result

In Arduino, the type int is a 16-bit value,
so using & between two int expressions causes 16 simultaneous AND operations to occur.
In a code fragment like:

    int a =  92;          // in binary: 0000000001011100
    int b = 101;         // in binary: 0000000001100101
    int c = a & b;      // result:    0000000001000100, or 68 in decimal.


Each of the 16 bits in a and b are processed by using the bitwise AND,
and all 16 resulting bits are stored in c, resulting in the value 01000100 in binary,
which is 68 in decimal.

One of the most common uses of bitwise AND is
    to select a particular bit (or bits) from an integer value, often called masking.
See below for an example



Bitwise OR (|)

The bitwise OR operator in C++ is the vertical bar symbol, |.
Like the & operator, | operates independently
   each bit in its two surrounding integer expressions,
   but what it does is different (of course). 


The bitwise OR of two bits is 1 if either or both of the input bits is 1, otherwise it is 0.
In other words:

    0  0  1  1    operand1
    0  1  0  1    operand2
    ----------
    0  1  1  1    (operand1 | operand2) - returned result

Here is an example of the bitwise OR used in a snippet of C++ code:

    int a =  92;         // in binary: 0000000001011100
    int b = 101;        // in binary: 0000000001100101
    int c = a | b;       // result:    0000000001111101, or 125 in decimal.




Example Program

A common job for the bitwise AND and OR operators
     is what programmers call Read-Modify-Write on a port.
On microcontrollers, a port is an 8 bit number
     that represents something about the condition of the pins.
Writing to a port controls all of the pins at once.

PORTD is a built-in constant that refers to the output states of digital pins 0,1,2,3,4,5,6,7.
If there is 1 in an bit position, then that pin is HIGH.
    (The pins already need to be set to outputs with the pinMode() command.)
So if we write PORTD = B00110001; we have made pins 2,3 & 7 HIGH.
One slight hitch here is that we may also have changeed the state of Pins 0 & 1,
    which are used by the Arduino for serial communications
    so we may have interfered with serial communication.

     Our algorithm for the program is:

    * Get PORTD and clear out only the bits corresponding to
    -      the pins we wish to control (with bitwise AND).
    * Combine the modified PORTD value with
    -      the new value for the pins under control (with biwise OR).

int i;             // counter variable
int j;

void setup()
{
    // set direction bits for pins 2 to 7,
    // leave 0 and 1 untouched   (xx | 00 == xx)
    DDRD = DDRD | B11111100;
    // same as pinMode(pin, OUTPUT) for pins 2 to 7
    Serial.begin(9600);

}//setup()


void loop()
{
     for (i=0; i<64; i++)
    {
          // clear out bits 2 - 7, leave pins 0 and 1 untouched (xx & 11 == xx)
         PORTD = PORTD & B00000011; 
         // shift variable up to pins 2 - 7 - to avoid pins 0 and 1
         j = (i << 2);     
        // combine the port information with the new information for LED pins        
        PORTD = PORTD | j;  
        // debug to show masking    
        Serial.println(PORTD, BIN);
        delay(100);
     }//for

}//loop()



Bitwise XOR (^)

There is a somewhat unusual operator in C++ called
    bitwise EXCLUSIVE OR, also known as bitwise XOR.
(In English this is usually pronounced "eks-or".)
The bitwise XOR operator is written using the caret symbol ^.

This operator is very similar to the bitwise OR operator |,
    only it evaluates to 0 for a given bit position when
    both of the input bits for that position are 1:

    0  0  1  1    operand1
    0  1  0  1    operand2
    ----------
    0  1  1  0    (operand1 ^ operand2) - returned result

Another way to look at bitwise XOR is that
    each bit in the result is a 1 if the input bits are different,
    or 0 if they are the same.

Here is a simple code example:

    int x = 12;             // binary: 1100
    int y = 10;             // binary: 1010
    int z = x ^ y;         // binary: 0110, or decimal 6


The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0)
    some of the bits in an integer expression.

In a bitwise OR operation if there is a 1 in the mask bit, that bit is inverted;
    if there is a 0, the bit is not inverted and stays the same.

Below is a program to blink digital pin 5.

// Blink_Pin_5
// demo for Exclusive OR

void setup()
{
      // set digital pin five as OUTPUT
     DDRD = DDRD | B00100000;
     Serial.begin(9600);

}//setup()


void loop()
{
      // invert bit 5 (digital pin 5), leave others untouched
      PORTD = PORTD ^ B00100000; 
      delay(100);

}//loop()


Reference:   http://arduino.cc/en/Reference/BitwiseAnd