Arduino Bare Metal LED blink

Arduino Bare Metal LED blink

Before we start writing code I want you to go through the schematic of Arduino Uno R3 ,There is a built-in led connected to PIN 13 of  the board ,we will blink this LED using bare metal code
PIN Diagram of Arduino Uno R3

We can blink LED in Arduino Uno R3 board using following code

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

We need to write equivalent to above code in bare metal form without using any pinMode , digitalWrite and delay API

//----------------------------------------------------

void setup() {
DDRB = DDRB | (1<<5); // Setting DDRB register 5th bit to HIGH
}                     // 5th bit in OUTPUT Mode

void loop() {

  volatile unsigned int i;
  PORTB = PORTB | (1<<5);  // Writing 1 to PORTB PB5 Pin
  for(i=0; i<65535; i++);  // worked as a delay loop function
  PORTB = PORTB & ~(1<<5); // Writing 0 to PORTB PB5 Pin
  for(i=0; i<65535; i++);  // worked as a delay loop function

}


//----------------------------------------------------

Explanation for delay loop:

Instead of using delay function i have used a for loop to generate a delay between toggling of LED
i have declared variable i as volatile because the compiler sees the for loop is empty because of optimization it does not executes it
by using volatile we simply telling the compiler not to do optimization of the code.



Full schematic of Arduino uno board



Incoming Search Terms:-

Bare Metal LED blink Arduino uno r3

Baremetal led blink arduino mega
Arduino led blinking with registers
Arduino led glow bare metal
arduino led glow with digitalwrite function
arduino led blink using cprogram
ardino baremetal led glow
ardino led blink using register
arduino led toggle without digitalwrite

No comments:

Post a Comment