how to Use Push Button Switch with Atmega32 and Atmel Studio

Microcontroller Topics
Post Reply
User avatar
Shehani
Lieutenant
Lieutenant
Posts: 61
Joined: Mon Aug 19, 2013 2:11 pm

how to Use Push Button Switch with Atmega32 and Atmel Studio

Post by Shehani » Wed Nov 13, 2013 2:48 pm

This tutorial is meant for beginners in the field of Atmel AVR programming. I hope that you already read my first tutorial How to blink LED using Atmega32 microcontroller. In most of the embedded electronic projects you may want to use a push button switch to give user inputs to the microcontroller. To use a push button switch with a microcontroller, first you should configure the corresponding pin as input. Then we can easily read the status of that input pin and make required decisions. There are two types of push button switches Push To On and Push To Off, here we are using Push To On switch. In this tutorial a press at the switch turns ON the LED for 3 seconds.
Push Button Switch
Push Button Switch
1.jpg (4.11 KiB) Viewed 5616 times
Circuit Diagram
Using Push Button Switch with Atmega32 using Atmel Studio
Using Push Button Switch with Atmega32 using Atmel Studio
2.jpg (74.7 KiB) Viewed 5616 times
As described in the first tutorial 16 MHz crystal is used to provide clock to the Atmega32 microcontroller. 10µF capacitor and 10K? resistor is used to provide Power On Reset (POR) during the startup of microcontroller. LED is connected to the first pin of PORTC (PC0) of the microcontroller and a resistor is used to limit current through it. Push Button Switch is connected to the first pin of PORTD (PD0) of the microcontroller and a pull down resistor is provided to make the input LOW whenever the switch remain unpressed.

Program

Code: Select all

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  DDRC |= (1<<PC0); //Nakes first pin of PORTC as Output
  // OR DDRC = 0x01;
  DDRD &= ~(1<<PD0);//Makes firs pin of PORTD as Input
  // OR DDRD = 0x00; //Makes all pins of PORTD input
  while(1) //infinite loop
  {
    if(PIND & (1<<PD0) == 1) //If switch is pressed
    {
      PORTC |= (1<<PC0); //Turns ON LED
      _delay_ms(3000); //3 second delay
      PORTC &= ~(1<<PC0); //Turns OFF LED
    }
  }
}

As mentioned in the first tutorial DDR is the Data Direction Register which determines whether each pin is input or output, PORT register is the output register which is used to write output to pins and PIN register is the PORT Input Register which is used to read data from input pins. DDRC |= (1<<PC0) and PORTC |= (1<<PC0) sets (makes 1) the 0th bit of the specified registers. DDRD &= ~(1<<PD0) and PORTC &= ~(1<<PC0) resets (makes 0) the 0th bit of the specified registers. PIND & (1<<PD0) reads the 0th bit of the PORTD register.



Article courtesy of electrosome.com
Post Reply

Return to “Microcontrollers”