EM10
EM10

Reputation: 815

Explain the C code instruction

The code below is used for programming microcontrollers. I want to know what the code below is doing. I know that '|' is OR and '&' AND but what is the whole line doing?

lcd_port = (((dat >> 4) & 0x0F)|LCD_EN|LCD_RS);

Upvotes: 1

Views: 243

Answers (5)

SolarBear
SolarBear

Reputation: 4619

It's hard to put into context since we don't know what dat contains, but we can see that:

  1. The data is right-shifted by 4 bits, so 11111111 becomes 00001111, for instance.
  2. That value is AND'ed with 0x0F. This is a common trick to remove unwanted bits, since b & 1 = 1 and b & 0 = 0. Think of your number as a sequence of bits, here's a 2-byte example :

    0011010100111010

    &

    0000000000001111


    0000000000001010

  3. Now the LCD_EN and LCD_RS flags are OR'ed. Again, this is a common binary trick, since b | 1 = 1 and b | 0 = b, so you can add flag but not remove them. So, if say LCD_EN = 0x01 and LCD_RS = 0x02,

    0000000000001010

    |

    0000000000000011


    0000000000001011

Hope that's clearer for you.

Upvotes: 3

Roddy
Roddy

Reputation: 68033

Some guesses, as you'll probably need to find chip datasheets to confirm this:-

lcd_port is probably a variable that directly maps to a piece of memory-mapped hardware - likely an alphanumeric LCD display.

The display probably takes data as four-bit 'nibbles' (hence the shift/and operations) and the higher four bits of the port are control signals.

LCD_EN is probably an abbreviation for LCD ENABLE - a control line used on the port.

LCD_RS is probably an abbreviation for LCD READ STROBE (or LCD REGISTER SELECT) - another control line used on the port. Setting these bits while writing to the port probably tells the port the kind of operation to perform.

I wouldn't be at all surprised if the hardware in use was a Hitachi HD44780 or some derivative.

Upvotes: 1

Eric
Eric

Reputation: 2116

This code is shifting the bits of dat 4 bits to the right and then using & 0x0F to ensure it gets only those 4 least significant bits. It's then using OR to find which bits exist in that value OR LCD_EN OR LCD_RS and assigning that value to lcd_port.

Upvotes: 0

suspectus
suspectus

Reputation: 17258

It is shifting the variable data four bits to the right, then masking the value with the value 15. This results in a value ranging from 0-15 (four left-most bits). This result is binary ORd with the LCD_EN and LCD_RS flags.

Upvotes: 0

george
george

Reputation: 1628

It appears to be setting some data and flags on the lcd_port. The first part applies the mask 0x0F to (dat >> 4) (shift dat right 4) which is followed by applying the LCD_EN flag and then LCD_RS flag.

Upvotes: 0

Related Questions