I'm trying to write a code for an up/down binary counter. The task is to light up 8 leds (up counter)and then reverse the lighting order (down counter). I am trying to create an array of leds in my code but I don't know how to do so.Whenever I use PORTB[i] I get and error pointer required and if I use PORTB.i I also get an error how can i access the leds connected to portb ? It's my first experience with microcontrollers in general and I would really appreciate your help. Here's my code:
char LED_Direction at TRISB;
void main() {
int i;
LED_Direction=0x00;
PORTB=0x00;
//sbit LED_Array [8] = {PORTB.0,PORTB.1,PORTB.2,PORTB.3,PORTB.4,PORTB.5,PORTB.6,PORTB.7};
while(1)
{
for (i=0; i<8; i++)
{
//LED_Array [i] = 1;
PORTB[i]=1;
Delay_ms(1000);
//LED_Array [i] = 0;
PORTB.i=1;
}
for (i=7; i>-1; i--)
{
//LED_Array [i] = 1;
PORTB.i=1;
Delay_ms(1000);
PORTB.i=0;
//LED_Array [i] = 0;
}
}
}
Best Answer
PORTB is neither a structure nor is it an array (or pointer).
Each bit in the value you assign to it directly corresponds to a pin.
Your line of code near the beginning of main() which reads 'PORTB=0x00;' is the correct way to assign values to PORTB.
If you want the least-significant bit high with the rest low, then set it to 0x01 (0b00000001).
If you want the most-significant bit high with the rest low, 0x80 (0b10000000) is your value.
A 0x55 (0b01010101) or 0xAA (0b10101010) will set alternating bits high & low.
You can also use bit-shifting to set a particular bit, so (1 << 3) will set the 3rd bit, and so on.