setting porta in a for loop

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello,

I am going to run a for loop for 8 loops. During each run, I want to set the next pin of PORTA low and keep the others high, or vice versa:

#define row0 0x01;
#define row1 0x02;
#define row2 0x04;
#define row3 0x08;
#define row4 0x10;
#define row5 0x20;
#define row6 0x40;
#define row7 0x80;

So the question, is how do I increment the for loop counter "row" in the loop? row++?

for(i=0; i<8; i++)
{
PORTA = row[i];
row++; //Is this the correct way to do this?
}
Does this appear to be a practical way to implement this?
Thanks for any pointers.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

cnewbie wrote:

#define row0 0x01;
#define row1 0x02;
#define row2 0x04;
#define row3 0x08;
#define row4 0x10;
#define row5 0x20;
#define row6 0x40;
#define row7 0x80;

defines 8 independent makros of name rowX, not a variable, not an array.
If you want a table of random patterns, an initialized array is the right way:

char row[]={0x01,0x02,....0x80};

Quote:

So the question, is how do I increment the for loop counter "row" in the loop? row++?

You don´t have to. As you already increment i and use it as an index, you will get the next element with the next index:

for(i=0; i<8; i++)
{
PORTA = row[i];
// row++; //Is this the correct way to do this?
}

Quote:

Does this appear to be a practical way to implement this?
Thanks for any pointers.

For your special "walking 1" pattern, you could implement this more easily using a shift operation:

char m=0x1; // 1st pattern
for(i=0; i<8; i++)
{
PORTA = m;
m<<=1; //wil shift the pattern one bit to the left
}

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Actually you don't even need the m variable


PORTA = 0x01;
for(i=0;i<7;i++) {
  PORTA <<= 1;
}

note the above will turn on only 1 LED at any given time. If your goal is to to turn on 1 LED at a time, keeping the previously ones lit, a simple modification is required.


PORTA = 0x01;
for(i=0;i<7;i++) {
  PORTA <<= 1;
  PORTA += 1;
}

One more thing to note. The above code will happen too fast for your eye to perceive anything. Unless you are running the AVR at an incredibly slow speed. So you will need to add a delay into the loop between PORTA settings in order to see the visual efect.


PORTA = 0x01;
for(i=0;i<7;i++) {
  my_delay();
  PORTA <<= 1;
}

Writing code is like having sex.... make one little mistake, and you're supporting it for life.