I want to create a program in AVR assembly that will poll the state of a momentary pushbutton switch and toggle the state of an LED whenever the switch is pressed. I am using an Arduino Duemilanove with an ATMega328P chip. I have a pushbutton switch connected between digital pin 0 and ground, and an LED with 330 ohm resistor connected between digital pin 8 and +5V. Here is my code so far:
;==============
; Declarations:
.def temp = r16
.org 0x0000
rjmp Reset
;==============
Reset:
ser temp
out DDRB, temp ; set all pins on Port B to OUTPUT mode
ldi temp, 0b11111110 ; set pin 0 on Port D to INPUT mode
out DDRD, temp
clr temp
out PORTB, temp ; clear temp and set all pins on Port B to LOW state
ldi temp, 0b00000001 ; set pin 0 on Port D to HIGH state
out PORTD, temp
;==============
; Main Program:
switch:
in temp, PIND ; get state of pins on Port D
cpi temp, 0 ; compare result to 0 (pushbutton is pressed)
brne PC+3 ; if != 0, go check again
ldi temp, (1<<PB0) ; otherwise, write logic 1 to pin 0 of Port B
out PINB, temp ; which toggles the state of the pin
rjmp switch
Unfortunately all this does is light the LED and keep it on no matter how many times the button is pushed. I am basing this code off of a program found here that turns the LED on as long as the button is pushed. I simply want to extend that to hold the LED in its current state until the button is pushed again. Any suggestions?
PIND0to0by using a mask not wholePIND. Especially if your port is left floating (the lighting on the diode may change the level of floating pin and make thecpi temp, 0always wrong). Also, you may use theSBIinstruction to change single bits inPINB. Not sure this will work but I do not see other problems for the moment. - Juliensbi, but I can't seem to make it work. Using ` sbi PORTB0, 1` does not give the expected results. I see your point about button bounce though. Maybe a delay subroutine somewhere in the main loop would debounce the switch? - Josh Bensonsbi PORTB, 0(no need for a 1 as Sbi is for set bit (cbi clear bit)). Yes some delay after a press detection would debounce - Julien