Ex. In one byte it’s 00000000
Once input ‘A’ is triggered the byte will now sent via uart serial 00000001
If input ‘b’ is triggered the byte will sent 00000010
If ‘a’ and ‘b’ is triggered the byte will sent 00000011
The question is how do I code this?
I will be using all the bit since I have 8 variable
Welcome to the forum
Where are the inputs coming from ?
Just digital read
I have 8 button that need is attached to a UNO and need to compile the data to one byte and sent it out via UART each button will have its own bit
Is this a school exercise, or an actual application? That may change our advice.
It’s for a product prototype DEMO so it’s actual application but no need to be very stable since it’s just a prototype
Okay. So, will the number of inputs change? What you've described, it is true, can be encapsulated in one byte, but expanding to two bytes will drastically change the need.
As it is,
- Do a serial begin in setup
- in loop,
- Build your byte from your eight inputs
- send the byte(write it to serial)
- loop
Do you know what an array is and understand how to read the value of each element of an 8 element array, such as a list of pin numbers ?
Is anything in particular going to trigger the printing of the byte containing the 8 bit values ?
What have you tried? Please post your latest attempt.
something like this ?
click to see the code
const byte dipPins[] = {9, 8, 7, 6, 5, 4, 3, 2};
void writeByte(const byte b) {
for (int8_t i = 7; i >= 0; i--) Serial.write(bitRead(b, i) + '0');
Serial.println();
// here we actually print a human readable version of the byte
// for binary communicatoin it shoud be
// Serial.write(b);
}
void setup() {
Serial.begin(115200);
for (byte aPin : dipPins) pinMode(aPin, INPUT_PULLUP);
}
void loop() {
static byte oldValue = 0x42;
byte currentValue = 0;
for (byte aPin : dipPins) {
currentValue <<= 1;
currentValue |= (digitalRead(aPin) == HIGH) ? 0 : 1; // INPUT_PULLUP => inverse input
}
if (currentValue != oldValue) {
writeByte(currentValue);
oldValue = currentValue;
}
}
The number of input will stay at 8 values with all having only possibilities of being 1 and 0
Nothing is going to trigger the byte sent, it’s just gonna sent every 500ms
Yes
So, what of this isn't understood?
So the passing of 500ms is going to trigger sending the byte
Are there any other requirements that you have not mentioned ?
You may wish to look at the blink without delay() tutorial for ideas. Serial Basics tutorial might also help.
No other requirements
How do I build up byte ?
so take the demo code I provided and add a way to handle sending the data every 500ms
For extra information and examples look at
- Using millis() for timing. A beginners guide
- Several things at the same time
- Flashing multiple LEDs at the same time
I do it in my code by shifting left the content of my byte and adding the newly read bit as the first bit. so when you are done reading the 8 bits, your variable has all the bits in the right position
Thank you