Arduino Tips and Tricks

I will be compiling some useful tips for you guys in this page to help with your Arduino projects.

A faster way to read and write to / from digital pins.

Have you noticed how slow reading and writing digitals pins is with the:

digitalRead();

and

digitalWrite();

functions?

Well I sure have (and upon searching the internet, other people have as well.)

So, if you are building a project that requires faster read and write speeds than what you normally can get using the above functions, you should instead try using:

bitRead();

and

bitWrite();

functions.

They require just a little more knowledge of the specific Atmel microcontroller that is at the heart of your Arduino board, but it’s pretty simple to work out. For example, if you wanted to send a logic 1 (high) to digital pin13, you would normally do it like this:

digitalWrite(13, HIGH);

The Arduino IDE knows where digital pin 13 is connected on the microcontroller. So if you wanted to use the bitWrite function on digital pin 13, you first have to find out the PORT and pin number of that port, that digital 13 belongs to. To do this, we need the Arduino schematic (here’s a zoomed in area of the Arduino Nano containing a 328p microcontroller):
328pZoomedIn

The capital D’s represent the digital pins. We want digital pin 13 ‘D13’ this happens to be connected to PORTB pin 5 (PB5). So in order to send a logic 1 to digital pin 13 – using the bit Write function, we do it likes this:

bitWrite(PORTB,5,1);

In the brackets we first write in the port we’re concerned with, then the pin number of that port and then finally, we write in what we want that port pin to be (I.E. either a 1 or a 0 – in this case, it’s a 1).

And that’s it for the first tip, you will find that the speed of reading and writing pins is MUCH quicker with the bitRead and bitWrite methods compared to the standard digitalRead and digitalWrite methods.

 

More to come as I think of them.