#include <Streaming.h>
Print &cout {Serial};
constexpr byte DATA_PINS[] {2, 3, 4, 5, 6, 7};
template <typename T> void printBits(Print &cout, const T &value) {
constexpr uint8_t maxBits = (sizeof(T) * 8);
constexpr T mask = (static_cast<T>(0x01) << (maxBits - 1));
uint8_t i = 0;
while (i < maxBits) {
cout << (((value << i++) & mask) ? 1 : 0);
// Output a space after each nibble.
if (!(i - ((i >> 2) << 2))) {
cout << " ";
}
}
cout << endl;
}
template <size_t N> byte getByte(const byte (&pins)[N]) {
static_assert(N < 9); // One Byte -> max. 8 Pins!
byte result {0};
for (byte i = 0; i < N; ++i) { result |= (digitalRead(pins[i]) << i); }
return result;
}
void setup() {
Serial.begin(115200);
for (auto &pin : DATA_PINS) { pinMode(pin, INPUT); }
}
void loop() {
static byte lastResult {0xFF};
byte result = (PIND >> 2); // Ganzen Port D auf einmal auslesen und erste zwei Bit rausrotieren (D0/D1)
if (lastResult != result) {
cout << "Dezimal: " << _WIDTH(result, 2) << " Binär: ";
printBits(cout, result);
cout << "Mit getByte(): ";
printBits(cout, getByte(DATA_PINS)); // Datenpins sequentiell auslesen
lastResult = result;
}
}