HD44780 in 4bit mode connected to only ONE PORT on PIC

hd44780lcdpicpinsport

i am new to PIC programming. I am using MPLAB X + XC8 compiler. I have on a breadboard an PIC18F4550 connected to a HD44780 compatible LCD. Digging online i found out a routine to interface the PIC with the LCD controller, works ok on 8MHz internal osc.

LCD is connected to the PIC like this:
RB0 = D4
RB1 = D5
RB2 = D6
RB3 = D7
RD5 = RS
RD7 = E

In my code, all PORTB is used for Data lanes and from PORTD only RD5 and RD7 are defined for RS and E.

My question: How can i move RS and E pins to PORTB also , so the LCD uses a SINGLE PORT, not 2 ports. . Because if i define for example RS as RB4 and E as RB5 , the code that toggles the DATA lines is like this (PORTB = data_to_send) , so it toggles all PORTB pins , not just RB0..RB3 . How can i address/toggle a pin range (RB0..RB3) of a PORT and not the whole port?

Best Answer

There is two methods you can use:

  1. Address individual pins. In XC8 you have such variables as LATBbits.LATB3 which you can set to 1 or 0 to turn an individual pin on or off.
  2. Use bitwise operators and masks. You can "or" and "and" bits together to turn chunks of a port on or off, such as LATB &= 0xF0 will turn off the lower 4 bits. LATB |= 0x03 will then turn the lowest two bits on without changing any other bits.