I am not allowed to use the Arduino Library (or any Library) for this program. How would I check the input of a pin?

I found two different functions:

In Arduino.h:

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

Following digitalRead back to pgmspace.h:

#define __LPM_enhanced__(addr)  \
(__extension__({                \
    uint16_t __addr16 = (uint16_t)(addr); \
    uint8_t __result;           \
    __asm__ __volatile__        \
    (                           \
        "lpm %0, Z" "\n\t"      \
        : "=r" (__result)       \
        : "z" (__addr16)        \
    );                          \
    __result;                   \

For the first one, I don't know where bit and value come from and I just don't understand the second one at all.

  • This looks a very similar topic to your other recent question: How do I use masks to make it so pin 13 (PB7 and the LED) as output and then have pin 10 (PB4) as an input?. Please don't ask two very similar questions in the space of a couple of hours. – Nick Gammon Oct 5 '16 at 9:00
  • I asked this one first to see how to get an input. The other question was to see if use the same Data Port for both an input and an output. – kingcobra1986 Oct 5 '16 at 9:15
  • But it's the same project, right? You are just looking at the same problem in slightly different ways. – Nick Gammon Oct 5 '16 at 9:34
  • No I'll more than likely use this for every project I do and the other one, it just depends on the project. Where this one is just get any pin. The other question is how to deal with getting an input from the B data registry and changing the state of the light as an output in the same data registry. – kingcobra1986 Oct 5 '16 at 9:41
  • I changed the title of the other question to better describe that question. – kingcobra1986 Oct 5 '16 at 9:45

For reading, e.g., PB2, you would test


where PINB is the port input register and _BV(x) is a macro defined as (1 << (x)).

C.f. the datasheet for the relevant port names.

See also the Arduino tutorial on port manipulation.

| improve this answer | |
  • Can you explain what (1<< (x)) does please? – kingcobra1986 Oct 5 '16 at 6:52
  • @kingcobra1986: arduino.cc/en/Reference/Bitshift – Edgar Bonet Oct 5 '16 at 6:53
  • I'm sorry, I didn't mean what is a bit shift. I know it is a bit shift to the left by x. What does it do though? Is it for getting the correct pin from the register? Or does it do something else? – kingcobra1986 Oct 5 '16 at 6:57
  • It does exactly what you know it does: it shifts 1 by x places to the left. No more, no less. C.f. playground.arduino.cc/Code/BitMath – Edgar Bonet Oct 5 '16 at 7:02
  • 1
    @kingcobra1986 The PB2 is defined as bit position not a bit mask (which is needed for bit manipulation). – KIIV Oct 5 '16 at 7:33

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.