allenhuffman
Joined: 17 Jun 2019 Posts: 554 Location: Des Moines, Iowa, USA
|
Arduino compatible bit macros (bitSet, bitClear, etc.) |
Posted: Tue Feb 25, 2020 1:38 pm |
|
|
To aid in porting Arduino code over, I have my own macros that replicate the ones Arduino uses to set, test, clear, etc. bits. These is also a test program to use them all, but it's for standard C and would need a few changes to run on the PIC.
Source: https://subethasoftware.com/2020/02/07/arduino-compatible-bit-macros/
Code: | #ifndef BITMACROS_H
#define BITMACROS_H
// Bit macros, based on Arduino standard.
// https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/bit/
//
// x: the numeric variable to which to write.
// n: which bit of the number to write, starting at 0 for the least-significant (rightmost) bit.
// b: the value to write to the bit (0 or 1).
#define bit(n) (1 << (n))
#define bitSet(x, n) ((x) |= bit(n))
#define bitClear(x, n) ((x) &= ~bit(n))
#define bitRead(x, n) (((x) & bit(n)) !=0 )
#define bitWrite(x, n, b) ((b) ? bitSet((x), (n)) : bitClear((x), (n)))
/* Verification tests:
bool showBits (uint32_t value, unsigned int bits)
{
bool status;
//printf ("showBits (%u, %u)\n", value, bits);
if ((bits == 0) || (bits > sizeof(value)*8))
{
status = false;
}
else
{
// Must use signed to check against 0.
for (int bit = (bits-1); bit >= 0; bit--)
{
printf ("%u", bitRead(value, bit));
}
printf ("\n");
}
return status;
}
int main()
{
unsigned int value;
// Test bit()
for (unsigned int bit = 0; bit < 8; bit++)
{
printf ("bit(%u) = %u\n", bit, bit(bit));
}
printf ("\n");
// Test bitSet()
for (unsigned int bit = 0; bit < 8; bit++)
{
value = 0;
printf ("bitSet(%u, %u) = ", value, bit);
bitSet(value, bit);
showBits (value, 8);
}
printf ("\n");
// Test bitClear()
for (unsigned int bit = 0; bit < 8; bit++)
{
value = 0xff;
printf ("bitClear(%u, %u) = ", value, bit);
bitClear (value, bit);
showBits (value, 8);
}
printf ("\n");
// Test bitRead()
value = 0b10101111;
showBits (value, 8);
for (unsigned int bit = 0; bit < 8; bit++)
{
printf ("bitRead(%u, %u) = %u\n", value, bit, bitRead (value, bit));
}
printf ("\n");
// Test bitWrite - 1
value = 0x00;
showBits (value, 8);
for (unsigned int bit = 0; bit < 8; bit++)
{
printf ("bitWrite(%u, %u, 1) = ", value, bit);
bitWrite (value, bit, 1);
showBits (value, 8);
}
// Test bitWrite - 0
showBits (value, 8);
for (unsigned int bit = 0; bit < 8; bit++)
{
printf ("bitWrite(%u, %u, 0) = ", value, bit);
bitWrite (value, bit, 0);
showBits (value, 8);
}
printf ("\n");
return EXIT_SUCCESS;
}
*/
#endif // BITMACROS_H
// End of BitMacros.h |
_________________ Allen C. Huffman, Sub-Etha Software (est. 1990) http://www.subethasoftware.com
Embedded C, Arduino, MSP430, ESP8266/32, BASIC Stamp and PIC24 programmer.
http://www.whywouldyouwanttodothat.com ? |
|