How switches work
2008-09-10 by Jeremy
Hello, I'm pretty new to programming for the AVR. I am using an
ATmega8L with the Atmel Dragon connected to the Dragon Rider 500 from
Ecros Tech. I am programming using WinAVR and AVR Studio 4. I am working
on a Traffic Light project from Ecros as my first project.
(http://www.ecrostech.com/General/TrafficLights/Parts.htm
<http://www.ecrostech.com/General/TrafficLights/Parts.htm> )
I'm working with PortD on the mega8 and for right now I am just trying
to get the switch to turn the LED on PD0. I will post my code below but
here is my problem. I program the mega8 and right away the LED is turned
on when it should be off. When I press the switch attached to PD3, the
LED on PD0 turns off. When I press the switch attached to PD7 the LED on
PD0 turns brighter. If you look at the switch schematic
http://www.ecrostech.com/General/TrafficLights/images/SchemSwitch.gif
<http://www.ecrostech.com/General/TrafficLights/images/SchemSwitch.gif>
you will notice two switches in parallel. This is alright because
there are four switches total. Two for North and South attached to PD7
and two for East and West attached to PD3. I am not sure if it's a
problem with the pullups that is making the LEDs at PD0 turn on from the
start. I'm trying to make it so the LEDs turn On when PD3 is pressed and
off when PD7 is pressed. I have even tried to not set the internal
pullups and nothing changes...
The simulator seems to be doing everything correctly, it's after I
program it that things don't work as I expected.
Also on a quick note: If I don't have the second if statement to check
PD7 ( if((PIND & (1 << PD7)) != 0){ } ) then the switch at PD3 doesn't
work at all... It doesnt turn the LED brighter or off...
Here is my code:
#define F_CPU 8000000UL
#include <avr/io.h>
#define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define BIT(x) (0x01 << (x))
void init_io(void)
{
DDRD = 0x77;
// Set PD3 and PD7 as input and the rest as output 0b01110111
PORTD = (1 << PD3)|(1 << PD7); // Set the internal pullups
high
}
int main(void)
{
init_io(); //Set up the pins that control the input and
output
for (;;) //Loop forever
{
if((PIND & (1 << PD3)) != 0)
bit_set(PORTD, BIT(0)); // Same
as PORTD = (1 << PD0);
if((PIND & (1 << PD7)) != 0)
bit_clear(PORTD, BIT(0)); // Same
as PORTD = (0 << PD0);
}
}
[Non-text portions of this message have been removed]