Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Pls help me in únderstanding this code

Status
Not open for further replies.

somf0872

Member level 5
Joined
Oct 14, 2003
Messages
93
Helped
1
Reputation
2
Reaction score
0
Trophy points
1,286
Activity points
929
Can somebody help me that how the for loop is working in this code? I need some step by step explanation.

Kind regards,

--X--

.............

static volatile uint8_t led; // use volatile when variable is accessed from interrupts

int main(void)
{
unsigned char keys;


DDRB = 0xff; // use all pins on PortB for output
PORTB = 0xff;

DDRD = 0x00; // use all pins on port D for input
PORTD = 0xff; // activate internal pull-up


led = 1; // init variable representing the LED state


for (;;) { // loop forever
keys = ~PIND; // read input port with keys (active-low)
if ( keys & 1 )
led = 1;
else if ( keys & 2 ) // priority encoder: if multiple keys are pressed,
led = 2; // only the lowest key is recognized
else if ( keys & 4 )
led = 4;
else if ( keys & 8 )
led = 8;
else if ( keys & 0x10 )
led = 0x10;
else if ( keys & 0x20 )
led = 0x20;
else if ( keys & 0x40 )
led = 0x40;
else if ( keys & 0x80 )
led = 0x80;
if ( keys )
PORTB = ~led; // Set corresponding LED if key pressed
}
}
.............
 

alzomor

Advanced Member level 2
Joined
Jun 9, 2005
Messages
678
Helped
39
Reputation
78
Reaction score
8
Trophy points
1,298
Location
Cairo
Activity points
6,417
Hi

I can't understand :D found in you for loop

but I think it's so clear.
it's just an endless loop reading an input and setting the corresponding led


Salam
Hosssam
 

fiquran

Full Member level 1
Joined
Mar 10, 2005
Messages
99
Helped
17
Reputation
34
Reaction score
3
Trophy points
1,288
Activity points
2,087
Hi somf0872,

there is a problem with the for loop condition you have given above. is it related to PORTB?

thanks.
 

artem

Advanced Member level 4
Joined
May 22, 2003
Messages
1,350
Helped
126
Reputation
252
Reaction score
32
Trophy points
1,328
Location
Turkey
Activity points
13,450
BTW your code can be replaced by :
Code:
unsigned char keys

	for (;;)
	{
		keys = ~PIND; 		
		keys = keys & -keys;
		if(keys != 0)
			PORTB = ~keys;
	}

P.S,. really nice book to read https://www.jjj.de/fxt/fxtbook.pdf
 

    somf0872

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Top