Yeshvanth Muniraj
Published

Accessing I/O in ATmega328P (Arduino) using Assembly and C

This project is meant to teach how to access Digital IO pins in ATmega328P in Assembly as well as C code.

BeginnerProtip30 minutes25,621
Accessing I/O in ATmega328P (Arduino) using Assembly and C

Things used in this project

Story

Read more

Schematics

The fritzing file

Code

The .ino file for Assembly

C/C++
Provides basic info to the assembler about the assembly code.
extern "C" {
  // function prototypes
  void start();
  void forever();
}

void setup() {
  start();
}

void loop() {
  forever();
}

The .s file for Assembly

Assembly x86
Contains the assembly code
#define __SFR_OFFSET 0
 
#include "avr/io.h"

.global start
.global forever

start:
    SBI DDRB, 2    ; Set PB2 as Output
    SBI DDRB, 3    ; Set PB3 as Output
    CBI DDRB, 4    ; Set PB4 as Input
    SBI PORTB, 4   ; Enable pull-up resistor
    RET

forever:
L2: SBIS PINB, 4    ; Skips below statement if Push-button is not pressed
    RJMP L1
    SBI PORTB, 2    ; Turn ON LED -> PB2 if not pressed
    CBI PORTB, 3    ; Turn OFF LED -> PB3 if not pressed
    SBIC PINB, 4    ; Skips below statement if Push-button is pressed
    RJMP L2
L1: SBI PORTB, 3    ; Turn ON LED -> PB3 if pressed
    CBI PORTB, 2    ; Turn OFF LED -> PB2 if pressed
    RET

The .ino file for C Code

C/C++
The easy C code
void setup() 
{
  // put your setup code here, to run once:
  pinMode (10, OUTPUT);         // GPIO 10 as Output
  pinMode (11, OUTPUT);         // GPIO 11 as Output
  pinMode (12, INPUT);          // GPIO 12 as Input
  pinMode (12, INPUT_PULLUP);   // Enable pull-up 
}

void loop() 
{
  // put your main code here, to run repeatedly:
  if ( digitalRead(12) == LOW ) // Read the state of button
  {                             // Execute this if button-pressed
    digitalWrite (10, LOW);     // LED -> PB2 OFF
    digitalWrite (11, HIGH);    // LED -> PB3 ON
  }
  else
  {                             // Execute this if button not pressed
    digitalWrite (10, HIGH);    // LED -> PB2 ON
    digitalWrite (11, LOW);     // LED -> PB3 OFF
  }
}

Credits

Yeshvanth Muniraj

Yeshvanth Muniraj

20 projects • 35 followers
Hands-on experience in Embedded Systems and IoT. Good knowledge of FPGAs and Microcontrollers.

Comments