Originally Posted by
g.21
I'm using ports RD0-RD3
Usually, pin number 0 corresponds to the least significant bit. For example, see here. Better yet, look at the documentation provided by your compiler and/or microcontroller manufacturer.
You're using the other bit labeling order.
On a PIC, initializing pins RD0 to RD3 can be done using two ways: either pin by pin, or all pins (of port D) at once. TRIS is set to zero for outputs, nonzero (one, or bits set) for inputs. Thus, to set D0..D3 to outputs, you can use
Code:
TRISD0_bit = 0;
TRISD1_bit = 0;
TRISD2_bit = 0;
TRISD3_bit = 0;
or, setting D0..D7 as outputs,
Similarly, you can set each output pin state, or read each input pin state, either pin by pin, or the entire 8-pin port at once. This changes the pin D2 state:
Code:
RD2_bit = !RD2_bit;
and this sets D0, D2, D4, and D6, and clears D1, D3, D5, and D7:
Code:
PORTD = 85; /* 0b01010101 */
Unlike normal C programs, you must never return from your main(), but loop forever. For example:
Code:
void main(void)
{
unsigned char state = 0;
/* Set D0 .. D7 as outputs. */
TRISD = 0;
while (1) {
/* Set new state. */
PORTD = state;
/* Flip bits */
state++;
/* Delay 125ms. */
Delay_ms(125);
}
}
You'll probably have to add an #includes, but it depends on the compiler, environment, and/or PIC type, so I leave that up to you. (Sometimes the delay routines are named Delay_ms() (microc), or delay_ms(), and sometimes you need to include some other header to get it. It just depends on what tools you are using; the names vary a bit, but the logic is pretty much the same.)
The example should blink D0 four times a second (125ms = 0.125s on, then 0.125 off, so 1/(0.125s+0.125s) = 1/0.25s = 4 s-1 = 4 Hz), D1 twice a second, D2 once a second, D3 once every two seconds, D4 once every four seconds, D5 once every eight seconds, D6 once every 16 seconds, and D7 once every 32 seconds. Well, not exactly "blink", since each pin will be half the time on, then half the time off, so D7 will stay 16 seconds on, then 16 seconds off, and so on.
If you have one or more LEDs with suitable current-limiting resistors, stick the resistor between the port D pin and the LED's anode (usually the longer leg), and the LED's cathode (usually the shorter leg, and/or side with the flat edge or other mark) to GND.