I am trying to make this work. I expect to turn pin number 4 high. I am using ATMEga 2560. I intend to use low level programming not digital write. I can upload the sketch but the output is OFF. Can you help me. Please and Thanks
You need to study the datasheet and a pinout diagram more closely. In principle what you're trying to do is just fine except pins 4, 5 and 6 on PORTD are not exposed on the mega2560.
Thank you. The pinout diagram helped. I am thinking of trying to use digitalWriteFast. Which is faster? PORTD |= (1 << PG5) or digitalWriteFast(4, HIGH)?
They should be exactly the same speed in the example you asked about. The library contains some macros which translate the digitalWriteFast() functions into port manipulation commands, where this can be done, as the sketch is compiled.
But not all digitalWriteFast() functions can be converted into port manipulation functions so easilly. For example
digitalWriteFast(myPinArray[i], myValue);
probably cannot be converted and will revert to digitalWrite().
So setting bit 5 takes two clock cycles? That's interesting. Does the ATmega CPU have a barrel shifter, or something similar
My question is how that is achieved at run time in 2 cycles instead of 5+ cycles.
There is no barrel shifter (and in fact something like "var << shiftcount" creates a painfully slow loop.)
PORTB |= (1<<5);
is compiled into a singleinstruction:
sbi PORTB, 5
(compiler optimization essentially "un-shifts" the argument in the C statement.)
Converting a binary number to a single-bit bitmask is much easier than barrel shifting - a job for a "decoder" circuit. Here's the internal logic diagram for a 7442, which does 4 bits to 10 outputs:
For those reading this with question marks in their eyes, I get tired typing Serial.println(x) all the time so a simple macro, #define prt(x) Serial.println(x)solves that.