Try Embedded

Mega: two LED chasers on whole ports

Use what an Arduino Mega has that an Uno does not: complete 8-bit ports on its header. Drive PORTA and PORTC with one register write each to run two LED bars…

Basic · Intermediate

In a real product: Stadium scoreboard (Consumer electronics): Whole ports drive many LEDs in one write.

The Uno's header gives you pieces of three small ports. The ATmega2560 on the Mega has eleven ports, and several of them come out on the header as a complete, ordered row of eight pins. That makes one register write a whole 8-bit output: no loop of digitalWrite() calls.

What you'll learn

  • Pins 22 to 29 are PORTA bits 0 to 7, and pins 37 down to 30 are PORTC bits 0 to 7
  • DDRx sets the direction of a whole port, PORTx writes all eight pins in one instruction
  • Why the port writes are atomic: all eight LEDs change together, not one after another
  • Reading the pins back through PINx to check what the port is doing

How it works

Two 10-segment LED bars are wired to the Mega, eight segments each. The first goes to pins 22 to 29 (PORTA), the second to pins 37 to 30 (PORTC, whose bit 0 is pin 37). DDRA = 0xFF and DDRC = 0xFF make both ports outputs.

Each step the sketch lights one LED on PORTA with 1 << position and the mirror-image LED on PORTC with 1 << (7 - position), so the two lit LEDs move towards each other and past. It then prints PORTA and PINA, which agree because the pin follows what the port drives.

Try this

  • Light a growing bar instead of one LED: PORTA = (1 << (position + 1)) - 1.
  • Add PORTL (pins 49 down to 42) as a third bar.
  • Time one PORTA = write against eight digitalWrite() calls with micros().

sketch.ino

// Two LED chasers on whole ports of the Mega: PORTA is pins 22-29 (bit 0 first), PORTC is pins 37-30.
int position = 0;
int direction = 1;

void setup() {
  Serial.begin(9600);
  DDRA = 0xFF;  // every pin of PORTA is an output
  DDRC = 0xFF;  // and of PORTC
}

void loop() {
  PORTA = 1 << position;        // one write sets all eight pins
  PORTC = 1 << (7 - position);  // the mirror image on the other port
  delay(120);
  Serial.print("PORTA=");
  Serial.print(PORTA, BIN);
  Serial.print(" PINA=");
  Serial.println(PINA, BIN);
  position += direction;
  if (position == 7 || position == 0) direction = -direction;
}

Lessons behind it