NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Simple micro controlled light switch

August 20, 2012
by bakerboy
bakerboy's Avatar

I want to have a light turn on and off by using in PD0 as an input, when the pin is high an led connected to PC4 should be on, when it is low the led should turn off.

Below is my code i am trying to use to do this, it is a modified version of led_blink.

This is my first project after completing the guide.

I know its a code issue, just not sure where, any help would be amazing.

#define F_CPU 14745600

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

#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
    //Pin Definitions:
    //PC4 is led
    //PD0 is switch

int main() {
  // LED as output
  DDRC |= (1<<PC4);
  // Set PD 4 as input
  DDRD &= ~(1<<PD0);

  // loop keeps looking forever
  while(1) {
    //if pin is high turn on LED
 if(PIND & (1<<PD0)) {

 // Turn on led 
 PORTC |= (1<<PC4);
  }
 // if pin is low turn off led
if(PIND & ~(1<< PD0)){

    //Turn off
    PORTC &= ~(1<<PC4);}
}
  return 0;

}
August 21, 2012
by pcbolt
pcbolt's Avatar

Hi bakerboy -

I think the problem might be on line 27...

if(PIND & ~(1<< PD0)){

This will not always evaluate to "true" when PD0 is low. The code block following the "if" expression will execute only if the value inside the parenthesis evaluates to something other than zero. If you step through the expression the way the MCU does it will compute this in order... (let's say all the pins of PORTD are low)

1<<PD0 = 0b00000001
~(1<<PD0) = 0b11111110
(PIND & ~(1<<PD0)) = 0b00000000 & 0b11111110 = 0b00000000
if (0b00000000) is "false" and will not execute the code block.

The easiest way to correct this problem is to replace line 27 with...

else{

If you want an expression that tests for a single low pin you can use...

if ((PIND & (1<<PD0)) == 0)

Post a Reply

Please log in to post a reply.

Did you know that NerdKits believes in the importance of a mixture of meaningful topics, clear instruction, and engaging projects? Learn more...