I am trying to get this pulser program to be fast enough for me. I am really close using digitalWrite(4,HIGH) followed by digitalWrite(4,LOW). I can't quite get the syntax down for using PORTD commands to speed this up. I have tried PORTD = 00010000 followed by PORTD = 00000000. What is the correct way to put pin 4 high , then low using direct port manipulation? Thanks in advance.
Maybe you forgot to set the direction of the pins? You can either do this the normal arduino way (pinMode(pin,OUTPUT)
), as this is a one-time operation and not usually time critical. Or you may set the data direction registers directly (DDRD |= 00010000
, or something. See Arduino Reference - Arduino Reference).
Also note the safer way to use direct port manipulation is not to write the hole register at once (like PORTD = 00010000
), as you will overwrite other outputs/inputs (or set/unset internal pullups in the case of inputs), but rather to use the OR and AND method that only change the pin/bit you want (unless you want to set all of them). Port D bit 0 and 1 are also the serial RX/TX used for uploading sketches btw, it might interfere with sketch uploading (I've just begun experimenting with that and it usually works OK, and if not either simply a retry or push the reset button on the arduino resolves it).
Like this:
PORTD |= 00010000;
or like this:
const int portBit = 4;
PORTD |= (1 << portBit);
The latter is a bit more descriptive, or it can be if given a more descriptive name. Though I would think the former is slightly faster.
And in the case of clearing it, and only that one:
PORTD &= ~(1<<portBit); // same as PORTD = PORTD & 11101111
Thanks for the help. This is what I ended up with and it works beautifully!
PORTD |= 0x10; // bitwise OR of that bit
PORTD &= ~0x10; // bitwise AND with inverted bits