Direct Port Manipulation: cannot assign port value to variable

I have set up a simple example with an arduino UNO receiving commands on one port (PORTC) and outputting data on another port (PORTD, with serial disabled). Using very basic code below, it works if PORTD is assigned a constant; however, if I try to assign it the value from another variable, it does not work.

byte count = 0;

void setup() {
  DDRC = DDRC & 0b11000000;
  DDRD = 0b11111111;
}

void loop() {
  // If not selected, don't run
  if ( (PINC & 0x03) != 0x02 ) return;
  // PORTD = 0xd4;
  PORTD = count;
  if (++count == 0xfe ) count = 0;
}

I then use an arduino MEGA to trigger the UNO and read the bits that are on PORTD. I trigger it every 100ms as a slow test. These are the bytes that are being put onto PORTD by the UNO:

E0,F6,22,36,50,71,95,B4,D0,E5,3,
31,55,72,97,A5,C3,E2,1,12,26,42,
73,93,B7,D3,E3,5,16,32,53,74,83,

which is obviously not counting.

If I replace PORTD = count with PORTD = 0xd4, then it works perfectly well. I have tried changing the type of count to uint8_t to no avail.

Any idea why I cannot set the value of PORTD to that contained in a variable? Thank you!

How are you triggering the PORTC pins? My suspicion is that when you put the trigger signal on PORTC, it is lasting long enough to run though loop multiple times, and the output of PORTD is changing so fast you don't catch it.

Agreed. You seem to have no state change detection on the input.

D'oh!! Thank you both. That is absolutely it.

I clear the trigger on the MEGA, but clearing the trigger happens after too many cycles on the UNO.

I have just put in a quick and stupid latch to require the trigger be cleared before going again:

void loop() {
  // If not selected, don't run
  if ( (PINC & 0x03) != 0x02 ) {
    processed = 0;
    return;
  }
  if (processed) return;
  
  PORTD = count;
  if (count++ == 0xfe ) count = 0;
  processed = 1;
}

Now it outputs perfectly:

3,4,5,6,7,8,9,A,B,C,D,
E,F,10,11,12,13,14,15,16,17,18,
19,1A,1B,1C,1D,1E,1F,20,21,22,23,
24,25,26,27,28,29,2A,2B,2C,2D,2E,
2F,30,31,32,33,34,35,36,37,38,39,

Thank you! I should have known that, but in my mind I had cleared the trigger on the "client" side and wasn't considering it...

Cheers

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.