Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lettinghenry/cc79ec43065eb69d55fd4997a63f8d66 to your computer and use it in GitHub Desktop.
Save lettinghenry/cc79ec43065eb69d55fd4997a63f8d66 to your computer and use it in GitHub Desktop.
Arduino: Port Manipulation
// DDRD (R/W) pin direction (0 = INPUT / 1 = OUTPUT)
// PORTD (R/W) pin state (INPUT: 0 = LOW / 1 = HIGH | OUTPUT: 0 = PULL-UP DIACTIVATED / 1 = PULL-UP ACTIVATED)
// PIND (R) pin state (INPUT ONLY: 0 = LOW / 1 = HIGH)
// bit(n) // calculates value of n-th bit (returns: 0 / 1)
// bitRead(byteName, n) // gets value of n-th bit of byte (returns: 0 / 1)
// bitSet(byteName, n) // sets value of n-th bit of byte to 1
// bitClear(byteName, n) // sets value of n-th bit of byte to 0
// bitWrite(byteName, n, val) // sets value of n-th bit of byte to 0 or 1
// byteName |= bit(1) | bit(0); // set bits 0 and 1 in a byte
// byteName &= ~bit(1) & ~bit(0); // clear bits 0 and 1 in a byte
// byteName ^= bit(1) | bit(0); // toggle bits 0 and 1 in a byte
DDRD = 0x00; // set digital pins 0-7 as INPUT
DDRD = 0xFF; // set digital pins 0-7 as OUTPUT
DDRD = B11110000; // set digital pins 0-3 as INPUT and digital pins 4-7 in as OUTPUT
DDRD &= ~bit(DDD2); // set digital pin 2 as INPUT
DDRD &= ~bit(DDD2); PORTD |= bit(PORTD2); // set digital pin 2 as INPUT_PULLUP
DDRD |= bit(DDD2); // set digital pin 2 as OUTPUT
PORTD = 0x00; // set digital pins 0-7 as LOW
PORTD = 0xFF; // set digital pins 0-7 as HIGH
PORTD = B11110000; // set digital pins 0-3 as LOW and digital pins 4-7 as HIGH
PORTD &= ~bit(PORTD2); // set digital pin 2 as LOW
PORTD |= bit(PORTD2); // set digital pin 2 as HIGH
bitRead(PIND, PIND2); // read state of digital pin 2 (0 = LOW, 1 = HIGH)
PORTD ^= bit(PORTD2); // toggle state of digital pin 2
PORTD ^= bit(PORTD2) | bit(PORTD3); // toggle state of digital pins 2 & 3
/*
ARDUINO PORT
PIN NAME
------- ----
0 PD0
1 PD1
2 PD2
3 PD3
4 PD4
5 PD5
6 PD6
7 PD7
8 PB0
9 PB1
10 PB2
11 PB3
12 PB4
13 PB5
A0 PC0
A1 PC1
A2 PC2
A3 PC3
A4 PC4
A5 PC5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment