Unable to read the input pin in AVR ATMEGA328p

Discussion in 'Embedded Systems and Microcontrollers' started by praveenmax, Dec 27, 2016.

  1. praveenmax

    Thread Starter New Member

    Apr 26, 2016
    5
    0
    Hello all,
    I am trying to read the pin PB0 which is an internal pull-up resistor input pin. In my code logic,
    • if PB0 is HIGH then execute if-block
    • if PB0 is LOW then execute else-block
    But when I connect PB0 to GND pin, it is still executing the if-block. Since I have connected some LEDs in PORTD which wont turn ON in IF block, I am sure that it is executing IF block.

    Code (Text):
    1. #include<avr/io.h>
    2. #include<util/delay.h>
    3.  
    4. int main(void)
    5. {
    6.      //For testing
    7.      DDRD =0b11111111;
    8.      PORTD =0b00000000;
    9.  
    10.      //CORRECTED CODE
    11.      DDRB |=(1<< PB1);// PB1 -output
    12.      DDRB &=~(1<< PB0);// PB0 -input
    13.      PORTB |=(1<< PB0);// Activated pullup in PB0
    14.      PORTB &=~(1<< PB1);// PB1 low
    15.  
    16.      while(1)
    17.      {
    18.           _delay_ms(100);
    19.          if( PINB &(1<<PB0))
    20.          {
    21.                 PORTD =0x00;
    22.          }
    23.          else
    24.          {
    25.                 PORTD =0xFF;
    26.          }
    27.  
    28.          _delay_ms(500);
    29.       }
    30. }
    Moderator edit: added code tags.
     
  2. MrChips

    Moderator

    Oct 2, 2009
    17,119
    5,294
    Remove the PINB test.
    Can you make the LEDs on PORTD flash (with suitable delays inserted into the code)?
    Code (Text):
    1. while(1)
    2. {
    3.   PORTD = 0;
    4.   _delay_ms(500);
    5.   PORTD = 0xFF;
    6.   _delay_ms(500);
    7. }
     
  3. dannyf

    Well-Known Member

    Sep 13, 2015
    2,196
    421
    maybe you shouldn't be so sure.
     
Loading...