You probably notice that you just can’t use port D lights by simply setting the port as an output as you would expect. That’s because you have to set port D to be digital first.
How To Set PORTD to Be Digital
Setting portd to be digital is really easy, all you have to do set the EBDIS bit to 1. This bit is part of the MEMCON register.
Here is the code used to set EBDIS to 1.
MEMCONbits.EBDIS=1;
Light Them Up
The following code lights up the lights one at a time from right to left. You should be able to understand what’s going on if you followed my previous PIC18 Explorer Board tutorials, if not I recommend that you do.
#include <p18f8722.h> // include the respective pic file #include <delays.h> #pragma config OSC=HS void main () { int count=0; TRISD=0; MEMCONbits.EBDIS=1; while(1) { if(count>8) count=0; switch(count) { case 0: PORTD=0x00; // binary 0b00000000 , decimal 0 break; case 1: PORTD=0x01; // 0b00000001 , 1 break; case 2: PORTD=0x03; // 0b00000011 , 3 break; case 3: PORTD=0x07; // 0b00000111 , 7 break; case 4: PORTD=0x0f; // 0b00001111 , 15 break; case 5: PORTD=0x1f; // 0b00011111 , 31 break; case 6: PORTD=0x3f; // 0b00111111 , 63 break; case 7: PORTD=0x7f; // 0b01111111 , 127 break; case 8: PORTD=0xff; // 0b11111111 , 255 break; } Delay10KTCYx(0); count++ } }
Knowing Some Math Pays Off
We can replace that whole switch with one line.
#include <p18f8722.h> // include the respective pic file #include <delays.h> #include <math.h> #pragma config OSC=HS void main () { int count=0; TRISD=0; MEMCONbits.EBDIS=1; while(1) { if(count>8) count=0; PORTD=pow(2,count)-1; // PORTD = 2^count - 1 Delay10KTCYx(0); count++; } }
Now Try This
Now that you are a port d expert try to replicate what I have in the following video.