Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: How switches work

2008-09-11 by Graham Davies

--- In AVR-Chat@yahoogroups.com, "Jeremy" <luminare@...> wrote:

> ... I am using an ATmega8L with the
> Atmel Dragon connected to the Dragon
> Rider 500 ... 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'm afraid my eyes glaze over when I try to reverse engineer your 
code, so can I instead offer some code that works and some general 
advice?  Below is a program that turns on the LEDs on bit 0 
(East/West green) when you press either SW3 or SW4 (East/West traffic 
sensors) and the LEDs on bit 4 (North/South green) when you press 
either SW1 or SW6 (North/South traffic sensors).

#include <avr/io.h>

int main( void )
{
   DDRD = 0x77;

   while ( 1 )
   {
      unsigned char switches;
      switches = ~PIND & 0x88;

      if ( switches & 0x08 )
         PORTD = 0x01;
      else if ( switches & 0x80 )
         PORTD = 0x10;
   }

   return ( 0 );
}

My advice is not to try to do too much in any given C statement.  In 
your 'if' statements, you are 1) reading a port, 2) selecting a bit 
from that port, 3) testing its value and 4) deciding what to do about 
it.  That makes it hard to read and understand.  By contrast, I have 
separated out the operation of reading the port, flipping the value 
(so that the bits read as one when the switch is closed rather than 
as zero per the hardware) and masking off the bits that are not 
switches.  Then I have a variable to test in the 'if' statements 
using clear and simple logic.  It reads 'if the switch at bit 3 is 
closed, turn on just the LED at bit 0, otherwise if the switch at bit 
7 is closed, turn on just the LED at bit 4'.  Try to express what you 
want to happen directly in the logic of the code, step by step, 
rather than sqeezing as much as possible into a small space.

Graham.
www.ecrostech.com

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.