Avr interfacing a switch

In this tutorial we check how to interface a push button to an Atmega8.

Here we will connect an external button to give input to a AVR. Button is connected to 5v if button pressed then delay of led lights changes if released then.here the program is configured in such a way that one pin B1 of Port B is configured as input and pin B0 as output.The input pin checks whether high or low is received and toggles the output pin.

Circuit Diagram

switch

Program

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

int main()
{
	DDRB |= 1<<PINB0;
	DDRB &= ~(1<<PINB1);
	PORTB |= 1<<PINB1;
	while(1)
	{
		PORTB ^= 1<<PINB0;
		if(bit_is_set(PINB,1))
		{
			_delay_ms(100);
		}
		else
		{
			_delay_ms(500);
		}
	}
}

Use  the  same  Makefile
Change the TARGET name with the file name of the above program
Use the  commands  in  sequence

make elf

make hex

make flash

Switch in action

Happy Hacking 🙂

Avr LED Blinking

This program explains hello world LED blinking program.In this program an LED is connected through a resistor to PINB0.

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

int main()
{
	DDRB |= 1<<PINB0;
	while(1)
	{
		PORTB |= 1<<PINB0;
		_delay_ms(100);
		PORTB &= ~(1<<PINB0);
		_delay_ms(100);
	}
}

The above program makes PINB0 blink with 100ms delay.
Compile and upload the hex file.You can use the blow make file for the whole process

CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
AVRDUDE = avrdude
REMOVE = rm -f

MCU =atmega8

TARGET = blink
SRC = $(TARGET).c

AVRDUDE_PROGRAMMER = dapa
AVRDUDE_PORT = /dev/parport0 
AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex

elf:
	$(CC) -mmcu=$(MCU) -Os -o $(TARGET).elf $(SRC)
hex:
	$(OBJCOPY) -j .text -j .data -O ihex  $(TARGET).elf $(TARGET).hex
flash:
	$(AVRDUDE) -p m8 -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) $(AVRDUDE_WRITE_FLASH)
clean:
	$(REMOVE) $(TARGET).hex $(TARGET).elf $(TARGET).c~

When your program name changes change name of the TARGET variable in Makefile.
Use the commands in sequence

make elf

make hex

make flash

HelloWorld in action

Happy Hacking 🙂