# Help Me Understand Bitmath

Can someone help me understand the bitmath used in the programming of TFT displays?

I can make sense of the DDR settings and the port masking but I am getting lost on the splitting of the 8 bit data word across the ports.

Here is my fix to the UTFT library code for the DDR bits on a Mega 2560:

``````void UTFT::_set_direction_registers(byte mode)
{
#if defined(USE_UNO_SHIELD_ON_MEGA)
// UPDATED pin mapping for SEEDV10 TFT screen on Mega 2560
// Arduino Pin	LCD Pin	Port (Mega 2560)
// D2	        D8	    PE4 ( OC3B/INT4 )
// D3	        D9    	PE5 ( OC3C/INT5 )
// D4	        D10	    PG5 ( OC0B )
// D5         	D11		PE3 ( OC3A/AIN1 )
// D6        	D12		PH3 ( OC4A )
// D7	        D13		PH4 ( OC4A )
// D8        	D14		PH5 ( OC4A )
// D9       	D15		PH6 ( OC4A )
// WRONG DDR bits
// DDRH = 0x18;
// DDRG = 0x20;
// DDRE = 0x3B;
// CORRECT DDR bits
DDRH = 0x71; // 01111000
DDRG = 0x20; // 00100000
DDRE = 0x31; // 00110001
``````

And then I am trying to make sense of how they were splitting up the 8bit data word:

``````			PORTG &= ~0x20;  // 00100000 - PG5
PORTG |= (VH & 0x10)<<1;  // select bit 4 of the char 00010000 and shift left by 1? = 0010000

PORTH &= ~0x18; //00011000 - PH3/PH4
PORTH |= (VH & 0xC0)>>3;  // select bits 7 and 8 of the char 11000000 and shift right by 3? = 00011000

PORTE &= ~0x3B; // 00110110 - PE1/PE2/PE4/PE5
PORTE |= (VH & 0x03) + ((VH & 0x0C)<<2) + ((VH & 0x20)>>2);
``````

Are my comments correct? I see how we shift the bits into G and H but E is wrong. Then I need to update the code for the correct port mapping.

Any guidance? :’(

This is what I came up with:

``````	G stays the same
PORTG &= ~0x20;
PORTG |= (VH & 0x10)<<1;
PORTH &= ~0x71; // 01111000
PORTH |= (VH & 0xF0)>>1;  // 01111000
PORTE &= ~0x31; //00110001
PORTE |= ((VH & 0x01)<<3) +((VH & 0x20) >> 4);
``````

Well, now that I am done laughing at my binary mistakes, I have what I believe is the proper port mapping for the Seeed TFT V1.0 shield on a Mega.

However it still does not work, I have compared all data to the working TFT library and am stumped.

Can anyone help?

``````// DDR settings
DDRE &=~ 0x38;
DDRG &=~ 0x20;
DDRH &=~ 0x78;

// port to byte mapping
PORTE |= ((VH<<4) & (0x30));
PORTG |= ((VH<<3) & (0x20));
PORTE |= ((VH & 0x08));
PORTH |= ((VH>>1) & (0x78));
``````