I'm using the following code to test some GPIO while I mess around with the PIC18F45K20 demo board. I realised something was strange when I couldn't increment a value and see it reflected on the LEDs after writing it to the port. Any idea why that is? I'm using the C18 compiler with MPLABX IDE v3.05
Using aPICkit3 with this demo kit: http://www.microchip.com/DevelopmentTools/ProductDetails.aspx?PartNO=dm164130-4
#pragma config FOSC = INTIO67
#pragma config WDTEN = OFF, LVP = OFF
#define TIMER T0CON
#include "p18f45k20.h"
void delay();
void delay() {
int counter = 0;
for (counter = 0; counter<1000; counter++);
}
void main(void) {
unsigned char d = 0;
TRISD = 0; // all bits of portd are set 0 as output
PORTD = 0; // deactivate all led's
while (1) {
d++;
PORTD = d;
delay();
}
}
1 Answer 1
On PICs, you read from PORT and write to LAT. Replace PORTD with LATD. It's also not a bad idea to declare counter
as volatile int counter = 0;
. Don't forget {}
after for(counter = 0; counter<1000; counter++)
.
-
\$\begingroup\$ Replaced PORTD with LATD, still no luck. Also, seems strange that I can write a hex value to PORTD and see it output if it's only for reading. \$\endgroup\$Sensors– Sensors2015年08月27日 15:01:20 +00:00Commented Aug 27, 2015 at 15:01
-
4\$\begingroup\$ @Sensors It's best practice to write to LAT and read from PORT. It's due to the history of PICs. Originally, PORT was used for both reading and writing. So-called "Read-Modify-Write" errors were common, so Microchip created the LAT registers for writing. The ability to write to PORT was retained for backwards compatibility. \$\endgroup\$bitsmack– bitsmack2015年08月27日 15:07:40 +00:00Commented Aug 27, 2015 at 15:07
-
2\$\begingroup\$ @MattYoung for delays, you do not need the brackets after your for loop. A semicolon is sufficient. \$\endgroup\$DerStrom8– DerStrom82015年08月27日 15:22:02 +00:00Commented Aug 27, 2015 at 15:22
-
1\$\begingroup\$ I agree with the suggestion to declare int counter as volatile. It's possible that the compiler is optimizing your delay loop out; volatile may prevent that from happening. Another possibility is to clear the watchdog timer every loop, something that the compiler should definitely not optimize out. You might also try clearing TRISE.PSPMODE manually; if it's set, it could override the D port. Manual says it's zero by default, but stranger things have happened. \$\endgroup\$Stephen Collings– Stephen Collings2015年08月27日 15:24:23 +00:00Commented Aug 27, 2015 at 15:24
-
1\$\begingroup\$ @derstrom8 I've seen enough stupid with Microchip compilers to not leave anything to chance. \$\endgroup\$Matt Young– Matt Young2015年08月27日 15:26:02 +00:00Commented Aug 27, 2015 at 15:26
LATD
instead ofPORTD
and also make your delay a lot slower. \$\endgroup\$