Microcontroller Embedded C Programming lecture 103| Applicability of bitwise operators : xor

  • Post author:
  • Post category:Blog

 

Applicability of bitwise operators : xor

 

 

In this article, let’s learn about the applicability of bitwise XOR operators. 

The XOR (^) operator you can use to toggle the bits. Let’s understand how XOR works.

You know that the XOR operator needs 2 operands: operand1 and operand2.

The result of the XOR operator will be 0 when both the operands are equal. When XOR operands are not equal, the result will be 1. That’s a truth table of bitwise XOR.

You can use this feature to toggle the bits or toggle the data.

Applicability of bitwise operators : xor
Figure 1. Toggling of bits

 

For example, here one statement Led_state = Led_state ^ 0x01. 

Now let’s assume that Led_state is 0, 0 ^ 1. Here operands are different. So, the output will be 1. Now the Led_state is 1. So, 1 ^ 1. Here operands are equal, so now Led_state becomes 0. Like that. So, the Led_state toggles.

You can use this feature of the XOR to toggle the GPIO, toggle the LED, or like that when you code for the microcontroller program.

Otherwise, you have to write the program something like this.

while(1) {
     if(LED == 0) {
         LED = 1;
     }else{
          LED = 0;
}

There is a while loop, while (1). If you want to toggle the LED continuously, you may have to do something like this. If(LED == 0), then make LED = 1, else make LED = 0. 

Suppose, if the Led_state is 0, then LED becomes 1. So, if the LED state is 1, then the LED becomes 0.  

Instead of writing all this code, you can just replace this with only one line of code, this one  LED ^= 1, which is used for toggling. 

Let’s use all these operators to write a program for our target board.

 

Exercise

Write a program to turn on the LED of your target board. 

For this exercise, we need the knowledge of 

– pointers

– bitwise operations

– hardware connections

you should know about the hardware connections. Because we are working with the hardware now. We are working with a microcontroller, and we are working with an external component that is LED. So, we have to know the hardware connections.

I will cover all these things in the following article. Let’s start doing this exercise.

 

FastBit Embedded Brain Academy Courses

Click here: https://fastbitlab.com/course1

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.