Take the 2-minute tour ×
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

So. I'm trying to read an input on the Arduino Nano using C++/AVR/Eclipse instead of the regular arduino IDE. The code below is working in the arduino IDE

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(digitalRead(5)){
    digitalWrite(13,1);
  }else{
    digitalWrite(13,0);
  }
}

I'm porting the code to AVR/C++ in Eclipse, regular blinking leds is working... but I can't read inputs for some reason...

#define F_CPU 16000000UL //16MHz
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;//Setting all portB pins to output (D13/PB5 - LED)
    DDRD = 0x00;//Setting all portD pins to input  (D5 /PD5 - INPUT)

    while(1){
        if(isset_bit(PORTD,PD5)){//if input... doesn't work?
            set_bit(PORTB,PB5);//Set output (Tested to be working)
        }else{
            clear_bit(PORTB,PB5);//Clear output
        }
    }
}
share|improve this question
    
Use the checkmark next to the answer rather than changing the title to indicate that the question has been answered. –  Ignacio Vazquez-Abrams yesterday
    
I know, but can't accept my own answer in the first 2 days after posting. I didn't want people to waste time on reading it, seeing it has been answered afterwards. –  FuaZe 18 hours ago

1 Answer 1

During the creation of this question I found out the answer... Though I wanted to share it with you guys for later reference. It has been quite a time since I have worked with AVR.

You should read pins from PINx

You should set pins in PORTx

Set DDRx to 1 for OUTPUT and to 0 for INPUT

^ This is fun because PIC/Microchip MCU's use 1 for input and 0 for output.

See code below:

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;
    DDRD = 0x00;

    while(1){
        if((PIND&(1<<PD5))){
            set_bit(PORTB,PB5);
        }else{
            clear_bit(PORTB,PB5);
        }
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.