Arduino Mega Direct Pin Control

Hello,

I would like to directly control a pin on the Arduino Mega. In my previous code used to control pin 9 on the Arduino UNO, I used the following function:

PORTB = B00000010; //Pin 9 = HIGH
PORTB = B00000000;// Pin 9 = Low

How can I achieve the same kind of pin control on the Mega? What are the direct port calling names as well as the sequence to turn it High/Low? Essentially, I would like to achieve the above on the Mega.

The register names are documented in the data sheet,
and they are defined with the same names by the Arduino system.

Locate the port and pin, manipulate just like on the other AVRs.

Since you’re fiddling with direct port bits, don’t forget to set the Port Direction Registers.

PORTB = B00000010; //Pin 9 = HIGH
PORTB = B00000000; // Pin 9 = Low

WARNING! This use of PORTB will set pins 8 though 13! To set just Pin 9:

PORTB |= B00000010; //Pin 9 = HIGH
PORTB &= ~B00000010; // Pin 9 = LOW

On the Arduino MEGA 2560, Pin 9 is "PH6" (Port H bit 6):

PORTH |= B01000000; // Pin 9 = HIGH
PORTH &= ~B01000000; // Pin 9 = LOW
1 Like

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