HI guys, marry Christmas!
I am going crazy on a quite simple topic. I am trying to write faster functions to write / read digital ports with register.. instead of digitalWrite / Read
If I understand the way, this two lines do:
Code:
DDRC = B00000001; // set analog 0 to OUTPUT
PORTC = B00000001; //set analog0 to HIGH
In BITreading i would have 1 or 0 in relation to pin state (I am building a custom protocol)
Code:
DDRC = B00000000; // set analog 0 input
PORTC = B00000000; // stop pull up
int BITreading = PINC & (1<<PC0); // get read value
In theory seems correct but don't works.
I try to print with serial BITreading, when I plug a 5v wire in the port, this is 1, but it takes many seconds to return to 0 after I remove the wire...quite strange.
When you remove the wire, there is nothing controlling the input, so the voltage "floats".
That is why it is recommended to use the internal pullup resistor, and have an external switch, like your wire, connect to ground, and read 0 as the active state.
Or, use an external pulldown resistor and connect the pin high like you did.
My suggestion would be to use digitalPinToBitMask, portOutputRegister, portOutputRegister and digitalPinToPort.
It seems that these functions have been moved into the official API since Arduino 1.0 but are not yet documented. But their use is quite simple.
During setup, store important pins in some global variables:
I am working on alternate implementation that will include functions like digitalRead/digitalWrite and classes for fast read/write. A preview of the classes is here http://arduino.cc/forum/index.php/topic,84044.0.html. I am working on a better version and will post it soon.
Hi Fatlib!! Are you the creator of fatlib library?!?!?
Thank you for the answer, but I don't want to use another library and I need to optimize flash space, I only need the 2 assembly / c ansi commands to do the same operation of digitalWrite HIGH or LOW faster.
You can't beat digitalWriteFast for size or speed.
digitalWriteFast(pin, HIGH) compiles to a single sbi two byte instruction for all Arduino 328 pins when pin is a constant. digitalWriteFast(pin, LOW) compiles to the two byte cbi instruction when pin is a constant. These instructions execute in two cycles or 125 ns on a 16 MHz cpu.
High address pins on the Mega take more flash and execute in more cycles.
Yes I wrote a number of SD libraries for FAT file systems.