# Dynamic port bits

#### varunme

Joined Sep 29, 2011
60
How can we access port bits using loops like this in mikroC ?

Rich (BB code):
#define _TOTAL_LIGHTS 5

for(i=0; i<_TOTAL_LIGHTS; i++)
{
if (PORTD. == 1)
{
PORTC. = 1;
}
else
{
PORTC. = 0;
}
}


Last edited by a moderator:

#### MrChips

Joined Oct 2, 2009
24,207
Use a switch/case statement.

#### varunme

Joined Sep 29, 2011
60
no way to access by for loop like this ?

#### MrChips

Joined Oct 2, 2009
24,207
No. The part after the dot is a member of a structure. It is not a variable.

#### AlexR

Joined Jan 16, 2008
732
I don't use MicroC so I don't know if there is some simple MicroC specific way to do it but the following method will work in any version of C.
Rich (BB code):
#define set_bit(ADDRESS,BIT) (ADDRESS |= (1<<BIT))

#define _TOTAL_LIGHTS 5

void some_function(void)
{
for(i = 0; i<_TOTAL_LIGHTS; i++)
{
if (test_bit(PORTD, i))
{
set_bit(PORTC, i);
}
else
{
clear_bit(PORTC, i);
}
}
}

#### ErnieM

Joined Apr 24, 2011
8,179
As long as you insist on using a loop you will be using more code and a longer time to execute then just doing a direct assignment:

Rich (BB code):
        LATC.B0 = PORTD.B0;
LATC.B1 = PORTD.B1;
LATC.B2 = PORTD.B2;
LATC.B3 = PORTD.B3;
LATC.B4 = PORTD.B4;

#### spinnaker

Joined Oct 29, 2009
7,835
I have often wanted to pass a port or latch in a function call myself. I have yet to figure out a way to do it.

pseudo code example

void foo(PortType port)
{

port = 1;

}

I realize you can do it with #defines but it would be nice to be able to pass a port or latch as a argument in a function.

#### ErnieM

Joined Apr 24, 2011
8,179
I have often wanted to pass a port or latch in a function call myself. ... I realize you can do it with #defines but it would be nice to be able to pass a port or latch as a argument in a function.
You can always pass the port by reference, ie, by passing the address of the port:

Rich (BB code):
void ClrPort(near unsigned char* Port);

void main (void)
{
ClrPort(&LATA);
}

void ClrPort(near unsigned char* Port)
{
*Port = 0;
}

#### varunme

Joined Sep 29, 2011
60
As long as you insist on using a loop you will be using more code and a longer time to execute then just doing a direct assignment:

Rich (BB code):
        LATC.B0 = PORTD.B0;
LATC.B1 = PORTD.B1;
LATC.B2 = PORTD.B2;
LATC.B3 = PORTD.B3;
LATC.B4 = PORTD.B4;
I am using 16F , so i cant use the LATCH

#### varunme

Joined Sep 29, 2011
60
Originally Posted by Patient
Doctor, it hurts when I do this.
Quote:
Originally Posted by Doctor
Then don't do that.
nice , hahhha

#### thatoneguy

Joined Feb 19, 2009
6,359
I have often wanted to pass a port or latch in a function call myself. I have yet to figure out a way to do it.
pseudo code example

void foo(PortType port)
{

port = 1;

}
I realize you can do it with #defines but it would be nice to be able to pass a port or latch as a argument in a function.
Just declare all of your variables globally. Buy a PIC with enough RAM first.