A question that pops up quite regularly is how to isolate bits in a word or byte to set or read. I think most novices struggle with the enigmatic "myVar & (1 << 4)" notation. The standard functions and libraries are at a loss beyond the highByte() and lowByte() macros.
Long story short, here's a deceptively simple union (a cousin of a struct) that help one to bit-bang, nybble, byte, and int your way through the same data.
I've included detailed instructions in the header file and a complete example that runs well on my Leonardo.
I hope you have some fun with it.
Some uses:
- Extracting high- and low-byte from an int
- Shifting four-bit quadrature nibbles for rotation measurement
- Setting up registers
- Sixteen boolean flags for your program all in one place
- I hope you'll give us some more examples!
Extract the .zip file in your \Arduino\libraries\ folder.
Credit where credit is due: This blog entry helped a lot with some of the details while I was starting out with creating the union. The version I've shared had some pretty complicated and inefficient predecessors!
http://www.utopiamechanicus.com/article/data-splitting-union-and-struct-c/
exploder_h.zip (4.17 KB)