GPIO input and output pins code

Hello everyone,

I have some questions about Arduino GPIO. I am using an Arduino Uno board and I would like to use GPIO to enable two Digital pins (pins 2 and 3) as inputs. I would like to be able to detect a LOW voltage (0.0 volts) as a 0 and a HIGH voltage (5.0 volts) as a 1.

I have been doing research online and I found an example about how to enable input and output GPIO pins in the setup function using PORT-D. And the example stated how to detect a HIGH or LOW voltage in the loop function. Here is the code that I am using:

void setup() {

Serial.begin(9600);

// This initialization statement is used to enable the eight GPIO pins used // by PORT-D. The purpose of the GPIO pins are to enable communication between // the Arduino and Raspberry Pi board. The value of 1 enables the output pins. DDRD = 0b11110000;

Serial.println("This is a GPIO program test.");

} void loop() {

Serial.println("Test before if statements."); if(PIND2 == 0) { Serial.println("Input pin 2 is in a low state."); } if(PIND2 == 1) { Serial.println("Input pin 2 is in a high state."); } Serial.println("Test after if statements.");

delay(5000);

}

The issue that I have with my sketch is that the if statements (the if statements in the loop function) are not executing. Neither of them. Only both serial print statements are executing. I have applied 0 voltages to pin2 and measured the voltage to verify; I have applied 5 voltages to pin2 and measured the voltage to verify. Yet again neither of the if statements execute.

What am I doing wrong with my code? I am new to using GPIO and I want to learn more about it.

Thanks for your help, David

PIND2 is a defined constant. It’s not going to give you the state of the pin. If you want that, you have to read the whole register and mask out the pin you want.

if(PORTD & (1 << PIND2)){
   // the pin is HIGH
}
if(!(PORTD & (1 << PIND2))){
  // the pin is LOW
}

DavidSV2017: Hello everyone,

I have some questions about Arduino GPIO. I am using an Arduino Uno board and I would like to use GPIO to enable two Digital pins (pins 2 and 3) as inputs. I would like to be able to detect a LOW voltage (0.0 volts) as a 0 and a HIGH voltage (5.0 volts) as a 1.

Just to be clear, the Arduino will detect anything below about 1 V as low and above 2.5 V as high. Check the data sheet if it matters.

It's not clear whether you're intentionally avoiding the Arduino pinMode() and digitalRead() functions, or whether you're unaware of them...

Would it not be easier to use digitalRead(...) instead of PIND2, PORTD, and masking?

Would it not be easier to use digitalRead(...) instead of PIND2, PORTD, and masking?

Easier, but slower, and perhaps prohibited by a "no arduino libraries" rule...

Hello all,

I decided to instead use digitalRead(). I think it will serve my needs.

Thanks for the replies,

David