1

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
        }
    }
}
  • Use the checkmark next to the answer rather than changing the title to indicate that the question has been answered. – Ignacio Vazquez-Abrams Apr 19 '15 at 16:21
4

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);
        }
    }
}
| improve this answer | |
  • This is interesting, what pins are you reading and writing? And how would you take an analog reading? – user2497 Sep 10 '17 at 9:58
  • 1
    @user2497 The microcontrollers use registers that you can read/write to/from. Arduino is an environment and a wrapper around this, to make it easier and more understandable. You should check the datasheet, to find which registers hold what. The registers are 1 byte (I bits), so you'll have to do some bit manipulation/arethmic and write it to the correct registers. – Paul Sep 10 '17 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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