AVR Tutorial – Experiment 3

Experiment 3

LED with switch

Objective – Controlling ON/OFF of an LED using switch

Pre-Requisites – AVR Motherboard , Mini USB cable, 12V DC Adapter, Software Setup (as described in introduction)

Theory – As of now, digital output on a LED was observed. In the given experiment it is required to control the LED based upon the input received from the switch. Here the switch is a push button. Push button have two states, OPEN state in which the two terminals of the push button are not connected two each other, this is the default state of push button.

The second state is CLOSE state, this state is achieved when the button is pressed, terminal of the push button are shorted. As per the input from switch the microcontroller can change the stage of LED. Interfacing microcontroller to read logic level voltages can be achieved easily. To provide logic levels for input the push button can be interfaced in two ways, PULL UP _or PULL DOWN _configuration. The hardware connections are discussed in connection/schematic part.


Connections :-
Nano <–> MV1
D2 (DDRD2) <–> Navi switch
D13 (DDRB5) <–> LED




// this code sets PD2 to an input with a pull-up disabled
#include <avr/io.h>
int main(void)
    DDRD &= ~(1 << DDD2); // Clear the PD2 pin
    // PD2 is now an input

    PORTD |= ~(1 << PORTD2); // turn On the Pull-up

    // to see output
    /* NANO pin 13 (DDB5), set pin 5 of PORTB for output*/
    DDRB |= _BV(DDB5);
        if( (PIND & (1<<PIND2)) > 0)
            // do something if PD2 is ON
            /* NANO pin 13 (DDB5), set pin 5 low to turn led off */
            PORTB &= ~_BV(PORTB5);
            // do something if PD2 is OFF
            /* NANO pin 13 (DDB5), set pin 5 high to turn led on */
            PORTB |= _BV(PORTB5);